package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.data.service.CabinetFileService;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.PaasFormDataHelper;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.AddMuchFieldPojo;
import com.xbongbong.paas.pojo.AssociatedBusinessAfterSavePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.parent.interfaces.DynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.ReRollBackEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicSaveDTO;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.RichTextEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.form.pojo.dto.ChildProductDTO;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.otherexpense.pojo.dto.OtherExpenseSaveDTO;
import com.xbongbong.pro.otherincome.pojo.dto.OtherIncomeSaveDTO;
import com.xbongbong.pro.payment.pojo.dto.PaymentDTO;
import com.xbongbong.pro.paymentsheet.pojo.dto.batch.PaymentSheetDTO;
import com.xbongbong.pro.paymentsheet.pojo.vo.batch.PaymentSheetAmountVO;
import com.xbongbong.pro.payplan.pojo.dto.PayPlanDTO;
import com.xbongbong.pro.payplansheet.pojo.dto.batch.PayPlanSheetDTO;
import com.xbongbong.pro.payplansheet.pojo.vo.batch.PayPlanSheetAmountVO;
import com.xbongbong.pro.product.pojo.ProductWithSupplierPojo;
import com.xbongbong.pro.product.pojo.ProductWithWarehousePojo;
import com.xbongbong.pro.product.pojo.StockNotifyPojo;
import com.xbongbong.pro.product.pojo.vo.ChildProductVO;
import com.xbongbong.pro.rabbitmq.producer.ConsistencySyncProducer;
import com.xbongbong.pro.service.toolbox.elasticsearch.help.ProEsHelper;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.BatchSeqOperationEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.domain.entity.ext.BomBillEntityExt;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditFixedLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditTemporaryLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.InstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.InventoryEntityExt;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentTaskEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseInvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.TransferEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkReportEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.PaymentLinkTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.ReturnedPurchaseStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.PaymentBaseEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CreditFixedLimitEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.dictionary.BatchSeqOperationEnum;
import com.xbongbong.saas.enums.dictionary.InventoryTypeEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.enums.dictionary.TransferTypeEnum;
import com.xbongbong.saas.enums.dictionary.WarehouseOriStockEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.InvoiceCommonHelper;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BatchSeqOperationModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.CreditFixedLimitModel;
import com.xbongbong.saas.model.CreditLimitModel;
import com.xbongbong.saas.model.CreditTemporaryLimitModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.saas.service.AssembleService;
import com.xbongbong.saas.service.BomBillService;
import com.xbongbong.saas.service.ClueService;
import com.xbongbong.saas.service.CommunicatePlanService;
import com.xbongbong.saas.service.CompetitorService;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CreditFixedLimitService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.CreditTemporaryLimitService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.DingRobotService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.InstockService;
import com.xbongbong.saas.service.InventoryService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.service.MarketActivityForStaticService;
import com.xbongbong.saas.service.MarketActivityService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.service.OtherExpenseService;
import com.xbongbong.saas.service.OtherIncomeService;
import com.xbongbong.saas.service.OutstockService;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.PaymentTaskService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductionOrderService;
import com.xbongbong.saas.service.PurchaseInvoiceService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.RefundService;
import com.xbongbong.saas.service.ReturnedPurchaseService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.service.SupplierContactService;
import com.xbongbong.saas.service.SupplierService;
import com.xbongbong.saas.service.TransferService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.WorkReportService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;

/**
 * model操作工厂
 * 创建时间： 2019/1/10 16:46
 * 修改时间： 2019/1/10 16:46 梁鲁江
 *
 * @author 梁鲁江
 */
@Service("proModelService")
public class ProModelServiceImpl implements ProModelService {

    private static final Logger LOG = LoggerFactory.getLogger(ProModelServiceImpl.class);

    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private CustomerModel customerModel;

    @Resource
    private CustomerService customerService;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private OutstockService outstockService;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private BomBillService bomBillService;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ContractService contractService;
    @Resource
    private ContactModel contactModel;
    @Resource
    private ContactService contactService;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    @Lazy
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private SupplierCommunicateService supplierCommunicateService;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private WorkReportService workReportService;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private CommunicatePlanService communicatePlanService;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private ReturnedPurchaseService returnedPurchaseService;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private SupplierService supplierService;
    @Resource
    private SupplierContactService supplierContactService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private PaymentService paymentService;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private ProductionOrderService productionOrderService;
    @Resource
    private ProductService productService;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferService transferService;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private AssembleService assembleService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private InstockModel instockModel;
    @Resource
    private InstockService instockService;
    @Resource
    private RefundService refundService;
    @Resource
    private RefundModel refundModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private ProEsHelper proEsHelper;
    @Resource
    private ConsistencySyncProducer consistencySyncProducer;
    @Resource
    private CabinetFileService cabinetFileService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private UserModel userModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private QuotationService quotationService;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private PurchaseInvoiceService purchaseInvoiceService;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private PaymentTaskModel paymentTaskModel;
    @Resource
    private PaymentTaskService paymentTaskService;
    @Resource
    private BatchSeqOperationModel batchSeqOperationModel;
    @Resource
    private DingRobotService dingRobotService;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private MarketActivityService marketActivityService;
    @Resource
    private ClueModel clueModel;
    @Resource
    private ClueService clueService;
    @Resource
    private ProductFormDataServiceImpl productFormDataService;
    @Resource
    private MarketActivityForStaticService marketActivityForStaticService;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private CreditLimitModel creditLimitModel;
    @Resource
    private CreditFixedLimitService creditFixedLimitService;
    @Resource
    private CreditFixedLimitModel creditFixedLimitModel;
    @Resource
    private CreditTemporaryLimitService creditTemporaryLimitService;
    @Resource
    private CreditTemporaryLimitModel creditTemporaryLimitModel;
    @Resource
    private PromotionActivityServiceImpl promotionActivityService;
    @Resource
    private OtherIncomeService otherIncomeService;
    @Resource
    private OtherExpenseService otherExpenseService;
    @Resource
    private CommonHelp commonHelp;

    @Resource
    private PaasDataFormDataServiceImpl paasDataFormDataService;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;
    @Resource
    private RichTextService richTextService;
    @Resource
    private PaasFormDataHelper paasFormDataHelper;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private CompetitorService competitorService;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;


    @Override
    @Deprecated
    public AfterSaveVO insert(FormDataAddDTO formDataAddDTO, PaasFormDataEntity paasFormDataEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        Long dataId = 0L;
        String corpid = formDataAddDTO.getCorpid();
        Integer saasMark = formDataAddDTO.getSaasMark();
        Integer businessType = formDataAddDTO.getBusinessType();
        String userId = formDataAddDTO.getUserId();
        String creatorId = paasFormDataEntity.getCreatorId();
        String creatName = "";
        if(creatorId != null){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            if (Objects.nonNull(user)){
                creatName = user.getName();
            }
        }
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.NEW;
        if (Objects.equals(1, formDataAddDTO.getIsBusinessRule())) {
            operateTypeEnum = OperateTypeEnum.RULE_NEW;
        }
        String userName = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatName : formDataAddDTO.getLoginUserName();
        if (Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID_PARAM) || Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID)) {
            // 外链新增的，人员叫外部人员
            userName = PaasConstant.OUT_LINK_USER_NAME;
        }
        userId = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatorId : userId;
        boolean isImport = Objects.equals(1, formDataAddDTO.getIsImport());
        JSONObject data = paasFormDataEntity.getData();
        //回款单or付款单标记
        boolean sheetFlag = false;
        //兼容审批移除上一步data放入的 ownerId, coUserId
        paasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.COUSERID.getAlias());
        paasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();
        Object richTextData = paasFormDataEntity.getData().remove(RichTextEnum.RICH_TEXT.getAttr());
        try {
            if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
                if (Objects.nonNull(formDataAddDTO.getProcessCreatorId()) && Objects.isNull(paasFormDataEntity.getOwnerId())) {
                    paasFormDataEntity.setOwnerId(formDataAddDTO.getProcessCreatorId());
                }
                Integer paasDataId;
                if (Objects.equals(1, formDataAddDTO.getIsBusinessRule())) {
                    // 业务规则专用
                    paasDataId = paasFormDataModel.insert(paasFormDataEntity, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                } else {
                    paasDataId = paasFormDataModel.insert(paasFormDataEntity);
                }
                dataId = paasFormDataEntity.getId();
                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataAddDTO.getExplainMap(), paasFormDataEntity.getData(), paasFormDataEntity.getSubFormData(), corpid, paasFormDataEntity.getId(), 0, userId);
                //富文本保存
                richTextService.saveFormRichText(formDataAddDTO, paasFormDataEntity, richTextData);
                //阶段推进器后置操作
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                paasDataFormDataService.afterSaveStage(saasFormSaveDTO);

                // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                // 解析标题
                if(!isImport){
                    Map<String, FieldAttrEntity> explainMap = formDataAddDTO.getExplainMap();
                    List<FieldAttrEntity> list = new ArrayList<>();
                    Iterator<String> iterator = explainMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String attr = iterator.next();
                        FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
                        list.add(fieldAttrEntity);
                    }
                    PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                    BeanUtil.copyProperties(paasFormDataEntity, paasFormDataEntityExt);
                    List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, data, list, paasFormDataEntityExt);
                    String title = "";
                    if(!formTitleList.isEmpty()){
                        formTitleList.forEach(titlePoJo->{
                            FieldAttrEntity fieldAttrEntity = explainMap.get(titlePoJo.getAttr());
                            if (Objects.nonNull(fieldAttrEntity) && ExplainUtil.isCombo(fieldAttrEntity.getFieldType())) {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put(titlePoJo.getAttr(), titlePoJo.getValue());
                                Object value = ItemUtil.analysisComboReturnStr(jsonObject, fieldAttrEntity);
                                titlePoJo.setValue(Collections.singletonList(value));
                            }
                        });
                        title = TitleUtil.getTitle(formTitleList);
                    }
                    if(StringUtil.isEmpty(title)){
                        title = "--";
                    }

                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_FORM_DATA), userName, paasFormEntityExt.getName(), title);
                    mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM_DATA, operateTypeEnum, paasFormDataEntity.getId().toString(),
                            title, memo, formDataAddDTO.getHttpHeader());
                }
                afterSaveVO.setFormDataId(dataId);
                return afterSaveVO;
            } else {
                if (businessType == null || businessType == 0) {
                    LOG.error("businessType为空");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                String logName = null;
                String memo;
                String serialNo = paasFormDataEntity.getSerialNo();
                String name;
                StringBuilder sb = new StringBuilder();

                List<ValidateDataDTO> needAddValidateDataDTO = null;
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
                XbbRefTypeEnum  xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
                SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo;
                RedundantTemplateTypeEnum workReportTypeEnum;
                FormDataAddVO formDataAddVO = new FormDataAddVO();
                switch (xbbRefTypeEnum) {
                    case CUSTOMER_MANAGEMENT:
                        data.remove(CustomerManagementEnum.ADD_CONTACT.getAttr());
                        data.remove("isBringCustomer");
                        data.remove("clueId");
                        paasFormDataEntity.setData(data);
                        // 设置已出库其他费用和出库金额的默认值
                        data.put(ContractEnum.OUTSTOCK_DISCOUNT_AMOUNT.getAttr(), 0);
                        data.put(ContractEnum.OUTSTOCK_OTHER_EXPENSE.getAttr(), 0);
                        CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
                        customerModel.insert(customerEntityExt);
                        dataId = customerEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setSubFormData(customerEntityExt.getSubFormData());
                        //addTime，updateTime 没有会导致评分不准确
                        paasFormDataEntity.setAddTime(customerEntityExt.getAddTime());
                        paasFormDataEntity.setUpdateTime(customerEntityExt.getUpdateTime());
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        customerService.afterSave(saasFormSaveDTO);
                        saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                        if (saasNeedRedundantAttrPoJo != null) {
                            needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                            // TODO 审批过来的数据是最后审批人的userId
                            for (ValidateDataDTO validateDataDTO : needAddValidateDataDTO) {
                                validateDataDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            }
                        }
                        if (!Objects.isNull(needAddValidateDataDTO)) {
                            paasFormDataService.batchAddContact(needAddValidateDataDTO, customerEntityExt.getId(), customerEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()), formDataAddDTO.getLoginUser(),ContactEnum.CUSTOMER_NAME.getAttr(),XbbRefTypeEnum.CONTACT);
                        }
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                            String isPublic = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), "");
                            String publicName = Objects.equals(isPublic, "1") ? PublicEnum.PUBLIC.getName() : xbbRefTypeEnum.getName();
                            Long clueId = formDataAddDTO.getClueId();
                            if(clueId != null && clueId > 0){
                                // 客户来自于线索转换
                                ClueEntityExt clueEntityExt = clueModel.getByKey(clueId, corpid);
                                JSONObject clueObj = clueEntityExt.getData();
                                String clueName = FastJsonHelper.getStringOrDefaultFromFormData(clueObj, ClueEnum.COMPANY_NAME.getAttr(), "");
                                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_CLUE_TRANS_CUSTOMER), userName, clueName, publicName, logName);
                                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, OperateTypeEnum.TRANSFORM, paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                            } else {
                                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, publicName, logName);
                                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, operateTypeEnum,
                                        paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                            }
                        }
                        // 添加统计数据
                        marketActivityForStaticHelp.addMarketActivity(paasFormDataEntity, xbbRefTypeEnum);
                        break;
                    case COMPETITOR:
                        // 外链竞争对手新增
                        paasFormDataEntity.setData(data);
                        CompetitorEntity competitorEntity = new CompetitorEntity();
                        BeanUtil.copyProperties(paasFormDataEntity,competitorEntity);
                        competitorModel.insert(competitorEntity);
                        Long id = competitorEntity.getId();
                        paasFormDataEntity.setDataId(id);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO,paasFormDataEntity);
                        competitorService.afterSave(saasFormSaveDTO);

                        //日志记录
                        saveDynamic(saasFormSaveDTO);

                        // 日志保存
                        if (!isImport){
                            String competitorName = FastJsonHelper.getStringOrDefault(data, CompetitorEnum.NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, XbbRefTypeEnum.COMPETITOR.getName(), competitorName);
                            mongoLogHelp.buildLog(corpid,userId,userName,
                                    OperateModuleTypeEnum.COMPETITOR,
                                    operateTypeEnum,
                                    competitorEntity.getId().toString(),
                                    competitorName,
                                    memo,
                                    formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CONTRACT:
                        data = paasFormDataEntity.getData();
                        data.remove(ContractEnum.ADD_PAYMENT.getAttr());
                        JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(data, ContractEnum.PRODUCT.getAttr());
                        data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
                        data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                        paasFormDataEntity.setData(data);
                        ContractEntityExt contractEntityExt = new ContractEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
                        // 关联产品特殊处理
                        /*JSONObject conProductDataList =contractEntityExt.getData();
                        saasSaveHelp.formatSelectProduct4Save(conProductDataList, ContractEnum.PRODUCT.getAttr());
                        contractEntityExt.setData(conProductDataList);*/
                        contractModel.insert(contractEntityExt);
                        // 保存合同后的操作
                        dataId = contractEntityExt.getId();
                        String signer = data.getString(ContractEnum.SIGN_PERSON.getAttr());
                        String signName = data.getString(ContractEnum.SIGN_NAME.getAttr());
                        Runnable sendRobotRunnable = () -> {
                            try {
                                dingRobotService.sendRobotByBusinessType(corpid, signer, signName,contractEntityExt,XbbRefTypeEnum.CONTRACT);
                            } catch (Exception e) {
                                LOG.error("发送群消息出错", e);
                            }
                        };
                        threadPoolBeanConfig.sendRobotMsgThreadPool().execute(sendRobotRunnable);

                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.getData().put(ContractEnum.PRODUCT.getAttr(),productArray);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                        contractService.afterSave(saasFormSaveDTO);

                        // TODO 会影响事务回滚
                        // 导入不走回款线程保存，为了保证回款数据及时保存
                        if(!isImport) {
                            Runnable runnable = () -> {
                                try {
                                    // 保存回款
                                    saveLinkPayment(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo);
                                    saveLinkPaymentSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo);
                                } catch (Exception e) {
                                    LOG.error("保存合同时保存回款", e);
                                }
                            };
                            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                        } else {
                            saveLinkPayment(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo);
                            saveLinkPaymentSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo);
                        }
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(ContractEnum.NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CONTRACT, operateTypeEnum,
                                    Objects.toString(paasFormDataEntity.getId(), ""), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CONTACT:
                        data.remove("isBringCustomer");
                        data.remove("clueId");
                        FormDataUtil.removeSystemData(data);
                        paasFormDataEntity.setData(data);
                        ContactEntityExt contactEntityExt = new ContactEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
                        contactModel.insert(contactEntityExt);
                        dataId = contactEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        contactService.afterSave(saasFormSaveDTO);

                        //创建成功机器人推送

                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CONTACT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case REFUND:
                        RefundEntityExt refundEntityExt = new RefundEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, refundEntityExt);
                        // 关联产品特殊处理
                        JSONObject refundDataList = refundEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(refundDataList, RefundEnum.PRODUCTS.getAttr());
                        JSONArray invoiceArray = refundDataList.getJSONArray(RefundEnum.INVOICES.getAttr());
                        JSONArray paymentSheetArray = refundDataList.getJSONArray(RefundEnum.PAYMENT_SHEETS.getAttr());
                        JSONArray paymentArray = refundDataList.getJSONArray(RefundEnum.PAYMENTS.getAttr());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.INVOICES.getAttr(), RefundEnum.INVOICES_LINKED_TEXT.getAttr(), RefundEnum.INVOICES.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.PAYMENT_SHEETS.getAttr(), RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENT_SHEETS.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.PAYMENTS.getAttr(), RefundEnum.PAYMENTS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENTS.getFieldType());
                        //合计退款金额在afterSave中处理，根据回款单是否创建成功来处理
                        Double refundAmount = getDoubleOrDefaultFromFormData(data, RefundEnum.REFUND_AMOUNT.getAttr(), 0D);
                        boolean paymentSheetIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.PAYMENT_SHEET.getCode());
                        boolean invoiceIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.INVOICE.getCode());
                        if (paymentSheetIsProcess) {
                            refundDataList.put(RefundEnum.REFUND_AMOUNT.getAttr(), 0D);
                        }
                        refundEntityExt.setData(refundDataList);
                        refundModel.insert(refundEntityExt);
                        dataId = refundEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.getData().put(RefundEnum.PRODUCTS.getAttr(),productArray);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        AssociatedBusinessAfterSavePojo refundAfterSavePojo = new AssociatedBusinessAfterSavePojo(invoiceArray, paymentSheetArray, paymentArray, refundAmount, reRollBackEntity, paymentSheetIsProcess, invoiceIsProcess);
                        refundService.afterSave(saasFormSaveDTO, refundAfterSavePojo);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(RefundEnum.REFUND_NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.REFUND, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case OUTSTOCK:
                    case CONTRACT_OUTSTOCK:
                    case OTHER_OUTSTOCK:
                    case RETURNED_PURCHASE_OUTSTOCK:
                    case WORK_ORDER_OUTSTOCK:
                    case PRODUCTION_MATERIEL_OUTSTOCK:
                        OutstockEntityExt outstockEntityExt = new OutstockEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, outstockEntityExt);
                        // 关联产品特殊处理
                        JSONObject outstockDataList = outstockEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(outstockDataList, OutstockEnum.PRODUCT.getAttr());
                        Long modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                        outstockEntityExt.setSysLong10(modelType);
                        outstockEntityExt.setData(outstockDataList);
                        outstockModel.insert(outstockEntityExt);
                        dataId = outstockEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存出库单后的操作
                        outstockDataList.put(OutstockEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(outstockDataList);
                        saasFormSaveDTO.setIsNew(true);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        outstockService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OutstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum(), OperateTypeEnum.NEW,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case RETURNED_PURCHASE:
                        JSONObject returnedPurchaseData = (JSONObject) paasFormDataEntity.getData().clone();
                        ReturnedPurchaseEntityExt returnedPurchaseEntityExt = new ReturnedPurchaseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, returnedPurchaseEntityExt);

                        // 关联产品特殊处理
                        JSONObject returnedPurchaseDataList = returnedPurchaseEntityExt.getData();
                        // 在插入之前对产品数据进行校验
//                        returnedPurchaseService.checkReturnedPurchaseProduct(returnedPurchaseDataList, true, returnedPurchaseEntityExt.getCorpid(), returnedPurchaseEntityExt.getId());
                        //关联付款单发票字段处理
                        JSONArray purchaseInvoiceArray = returnedPurchaseData.getJSONArray(ReturnedPurchaseEnum.INVOICES.getAttr());
                        JSONArray paySheetArray = returnedPurchaseData.getJSONArray(ReturnedPurchaseEnum.PAY_SHEETS.getAttr());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnedPurchaseEnum.INVOICES.getAttr(), ReturnedPurchaseEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.INVOICES.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getFieldType());
                        //合计退款金额在afterSave中处理，根据回款单是否创建成功来处理
                        Double returnedPurchaseAmount = getDoubleOrDefaultFromFormData(data, ReturnedPurchaseEnum.RETURNED_PURCHASE_AMOUNT.getAttr(), 0D);
                        boolean isPaySheetIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.PAY_SHEET.getCode());
                        boolean isPurchaseInvoiceIsProcess = processStartHelp.processFormJudge(corpid, XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
                        if (isPaySheetIsProcess) {
                            returnedPurchaseDataList.put(ReturnedPurchaseEnum.RETURNED_PURCHASE_AMOUNT.getAttr(), 0D);
                        }
                        productArray = saasSaveHelp.formatSelectProduct4Save2(returnedPurchaseDataList, ReturnedPurchaseEnum.PRODUCTS.getAttr());
                        // 设置待出库
                        returnedPurchaseDataList.put(ReturnedPurchaseEnum.STATUS.getAttr(), ReturnedPurchaseStatusEnum.WAIT_OUTSTOCK.getStatus());
                        returnedPurchaseEntityExt.setData(returnedPurchaseDataList);
                        //TODO 先检验权限
                        returnedPurchaseModel.insert(returnedPurchaseEntityExt);
                        dataId = returnedPurchaseEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        returnedPurchaseData.put(ReturnedPurchaseEnum.PRODUCTS.getAttr(),productArray);
                        paasFormDataEntity.setData(returnedPurchaseData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        AssociatedBusinessAfterSavePojo associatedBusinessAfterSavePojo = new AssociatedBusinessAfterSavePojo(purchaseInvoiceArray, paySheetArray, null, returnedPurchaseAmount, reRollBackEntity, isPaySheetIsProcess, isPurchaseInvoiceIsProcess);
                        returnedPurchaseService.afterSave(saasFormSaveDTO, returnedPurchaseEntityExt, associatedBusinessAfterSavePojo);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.RETURN_PURCHASE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case SALES_OPPORTUNITY:
                        OpportunityEntityExt opportunityEntityExt = new OpportunityEntityExt();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(paasFormDataEntity.getData(), SalesOpportunityEnum.PRODUCTS.getAttr());
                        BeanUtil.copyProperties(paasFormDataEntity, opportunityEntityExt);
                        // 关联产品特殊处理
                        //                    JSONObject oppProductDataList =opportunityEntityExt.getData();
                        //                    saasSaveHelp.formatSelectProduct4Save(oppProductDataList, SalesOpportunityEnum.PRODUCTS.getAttr());
                        //                    opportunityEntityExt.setData(oppProductDataList);

                        opportunityModel.insert(opportunityEntityExt);
                        dataId = opportunityEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.getData().put(SalesOpportunityEnum.PRODUCTS.getAttr(), productArray);
                        // 保存销售机会后的操作
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        opportunityService.afterSave(saasFormSaveDTO);
                        // 添加统计数据(如果关联的客户是由线索转化而来的)
                        marketActivityForStaticHelp.addMarketActivity(paasFormDataEntity,xbbRefTypeEnum);
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(SalesOpportunityEnum.NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.OPPORTUNITY, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case BOM_BILL:
                        JSONObject bomBillData = (JSONObject) paasFormDataEntity.getData().clone();
                        BomBillEntityExt bomBillEntityExt = new BomBillEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, bomBillEntityExt);
                        // 关联产品特殊处理
                        JSONObject bomDataList = bomBillEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(bomDataList, BomBillEnum.PRODUCT.getAttr());
                        JSONArray materiel = saasSaveHelp.formatSelectProduct4Save2(bomDataList, BomBillEnum.MATERIEL.getAttr());
                        bomBillEntityExt.setData(bomDataList);

                        bomBillModel.insert(bomBillEntityExt);
                        dataId = bomBillEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存BOM清单后的操作
                        paasFormDataEntity.setData(bomBillData);
                        bomBillData.put(BomBillEnum.PRODUCT.getAttr(),productArray);
                        bomBillData.put(BomBillEnum.MATERIEL.getAttr(),materiel);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        bomBillService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(BomBillEnum.NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.BOMBILL, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CUSTOMER_COMMUNICATE:
                        JSONObject communicateData = (JSONObject) paasFormDataEntity.getData().clone();
                        List<String> atUserIds;
                        if (communicateData.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr()) != null) {
                            JSONArray jsonArray = communicateData.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr());
                            atUserIds = JSONArray.parseArray(jsonArray.toJSONString(),String.class);
                        } else {
                            atUserIds = saasFormSaveDTO.getSaasNeedRedundantAttrPoJo().getAtUserIds();
                            if (Objects.nonNull(atUserIds) && atUserIds.size() > 0) {
                                communicateData.put(CustomerCommunicateEnum.AT_USERNAME.getAttr(), atUserIds);
                                paasFormDataEntity.setData(communicateData);
                            }
                        }
                        CustomerCommunicateEntityExt customerCommunicateEntityExt = new CustomerCommunicateEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, customerCommunicateEntityExt);
                        customerCommunicateModel.insert(customerCommunicateEntityExt);
                        dataId = customerCommunicateEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 新建跟进记录中@指定人员
//                        atUserIds.remove(userId);
//                        if (atUserIds.size() > 0) {
//                            customerCommunicateService.pushCustomerCommounicate(formDataAddDTO.getLoginUser(), formDataAddDTO.getBusinessType(), corpid, atUserIds, paasFormDataEntity, dataId);
//                        }
                        // 保存客户跟进记录后的操作
                        paasFormDataEntity.setData(communicateData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        //afterSave 这里面已经做了评分的处理
                        customerCommunicateService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                            // 可能跟进记录的来源于线索，没有关联客户
                            logName = logName == "" ? FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr(), "") : logName;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CustomerCommunicate, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case SUPPLIER_COMMUNICATE:
                        JSONObject supplierCommunicateData = (JSONObject) paasFormDataEntity.getData().clone();
                        List<String> supplierAtUserIds = new ArrayList<>();
                        JSONArray jsonArray = supplierCommunicateData.getJSONArray(SupplierCommunicateEnum.AT_USERNAME.getAttr());
                        if (Objects.nonNull(jsonArray)) {
                            supplierAtUserIds = JSONArray.parseArray(jsonArray.toJSONString(), String.class);
                        } else {
                            saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                            if(saasNeedRedundantAttrPoJo != null){
                                supplierAtUserIds = saasNeedRedundantAttrPoJo.getAtUserIds();
                            }
                        }
                        if (Objects.nonNull(supplierAtUserIds)) {
                            supplierCommunicateData.put(SupplierCommunicateEnum.AT_USERNAME.getAttr(), supplierAtUserIds);
                            paasFormDataEntity.setData(supplierCommunicateData);
                        }
                        SupplierCommunicateEntityExt supplierCommunicateEntityExt = new SupplierCommunicateEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierCommunicateEntityExt);
                        supplierCommunicateModel.insert(supplierCommunicateEntityExt);
                        dataId = supplierCommunicateEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存供应商跟进记录后的操作
                        paasFormDataEntity.setData(supplierCommunicateData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        supplierCommunicateService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_COMMUNICATE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case WORKREPORT_DAILY:
                    case WORKREPORT_WEEKLY:
                    case WORKREPORT_MONTHLY:
                    case WORK_REPORT:
                        businessType = XbbRefTypeEnum.WORK_REPORT.getCode();

                        WorkReportEntityExt workReportEntityExt = new WorkReportEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, workReportEntityExt);
                        workReportModel.insert(workReportEntityExt);
                        dataId = workReportEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存工作报告后的操作
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        workReportService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        Long reportDate = FastJsonHelper.getLongOrDefaultFromFormData(data, WorkReportFieldEnum.REPORT_DATE.getAttr(), 0L);
                        String reportName = DateTimeUtil.getStringEpochSecond(reportDate, DateTimeUtil.SDFDate);
                        workReportTypeEnum = RedundantTemplateTypeEnum.getByCode(saasFormSaveDTO.getSubBusinessType());
                        switch (workReportTypeEnum) {
                            case WORKREPORT_DAILY:
                                logName = "日报(“" + reportName + "“)";
                                break;
                            case WORKREPORT_WEEKLY:
                                logName = "周报(“" + reportName + "“)";
                                break;
                            case WORKREPORT_MONTHLY:
                                logName = "月报(“" + reportName + "“)";
                                break;
                            default:
                                break;
                        }
                        if(!isImport){
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, workReportTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.WORKREPORT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case COMMUNICATE_PLAN:
                        CommunicatePlanEntityExt communicatePlanEntityExt = new CommunicatePlanEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, communicatePlanEntityExt);
                        communicatePlanModel.insert(communicatePlanEntityExt);
                        dataId = communicatePlanEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存访客计划后的操作
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        communicatePlanService.afterSave(saasFormSaveDTO);

                        final String userNameStr = userName;
                        //需要新加一个推送
                        Runnable sendMsgRunnable = () -> {
                            try {
                                dingRobotService.sendRobotByBusinessType(corpid, creatorId, userNameStr,communicatePlanEntityExt,XbbRefTypeEnum.COMMUNICATE_PLAN);
                            } catch (Exception e) {
                                LOG.error("访客计划发送群消息出错", e);
                            }
                        };
                        threadPoolBeanConfig.sendRobotMsgThreadPool().execute(sendMsgRunnable);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicatePlanEnum.NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CommunicatePlan, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case SUPPLIER:
                        JSONObject supplierData = (JSONObject) paasFormDataEntity.getData().clone();
                        SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierEntityExt);
                        // 供应商关联产品特殊处理
                        JSONObject productList = supplierEntityExt.getData();
                        // 不做保存了，此字段仅作为表单冗余字段
                        //saasSaveHelp.formatSelectProduct4Save(productList, SupplierEnum.PRODUCT_LIST.getAttr());
                        productList.remove(SupplierEnum.PRODUCT_LIST.getAttr());
                        productList.remove(SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr());
                        supplierEntityExt.setData(productList);

                        supplierModel.insert(supplierEntityExt);
                        dataId = supplierEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setData(supplierData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);

                        supplierService.afterSave(saasFormSaveDTO);

                        saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                        if (saasNeedRedundantAttrPoJo != null) {
                            needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                            // TODO 审批过来的数据是最后审批人的userId
                            for (ValidateDataDTO validateDataDTO : needAddValidateDataDTO) {
                                validateDataDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                            }
                        }
                        if (!Objects.isNull(needAddValidateDataDTO)) {
                            paasFormDataService.batchAddContact(needAddValidateDataDTO, supplierEntityExt.getId(), supplierData.getString(SupplierEnum.SUPPLIER_NAME.getAttr()), formDataAddDTO.getLoginUser(),SupplierContactEnum.SUPPLIER_ID.getAttr(), XbbRefTypeEnum.SUPPLIER_CONTACT);
                        }
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case SUPPLIER_CONTACT:
                        JSONObject supplierContactData = (JSONObject) paasFormDataEntity.getData().clone();
                        SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierContactEntityExt);
                        supplierContactModel.insert(supplierContactEntityExt);
                        dataId = supplierContactEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setData(supplierContactData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        supplierContactService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER_CONTACT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PURCHASE:
                        JSONObject purchaseData = (JSONObject) paasFormDataEntity.getData().clone();
                        data = paasFormDataEntity.getData();
                        data.remove(PurchaseEnum.ADD_PAYPLAN.getAttr());
                        data.remove(PurchaseEnum.ADD_PAY_SHEET.getAttr());
                        data.remove(PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr());
                        paasFormDataEntity.setData(data);
                        PurchaseEntityExt purchaseEntityExt = new PurchaseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, purchaseEntityExt);

                        // 供应商关联产品特殊处理
                        JSONObject purchaseProductList = purchaseEntityExt.getData();
                        // 在插入之前对产品数据进行校验
//                        purchaseService.checkPurchaseProduct(purchaseProductList, true, purchaseEntityExt.getCorpid(), purchaseEntityExt.getId());
                        productArray = saasSaveHelp.formatSelectProduct4Save2(purchaseProductList, PurchaseEnum.PRODUCT.getAttr());
                        // 判断关联产品字段是否可见
                      /*  HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                        BeanUtil.copyProperties(formDataAddDTO, handlerExplainDTO);
                        boolean productCansee = commonHelp.attrCanSee(PurchaseEnum.PRODUCT.getAttr(), formDataAddDTO.getExplainMap(), handlerExplainDTO);
                        if(productCansee){
                            purchaseService.checkPurchaseProduct(purchaseProductList, true, purchaseEntityExt.getCorpid(), purchaseEntityExt.getId(), productCansee);
                            saasSaveHelp.formatSelectProduct4Save(purchaseProductList, PurchaseEnum.PRODUCT.getAttr());
                        }*/
                        purchaseEntityExt.setData(purchaseProductList);
                        purchaseModel.insert(purchaseEntityExt);
                        purchaseData.put(PurchaseEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(purchaseData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        dataId = purchaseEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        saasNeedRedundantAttrPoJo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
                        purchaseService.afterSave(saasFormSaveDTO);

                        if(!isImport) {
                            Runnable runnable = () -> {
                                try {
                                    // 保存回款
                                    saveLinkPayPlan(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, purchaseEntityExt);
                                    saveLinkPayPlanSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, purchaseEntityExt);
                                } catch (Exception e) {
                                    LOG.error("保存采购合同时保存付款单报错", e);
                                }
                            };
                            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                        } else {
                            saveLinkPayPlan(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, purchaseEntityExt);
                            saveLinkPayPlanSheet(saasFormSaveDTO, paasFormDataEntity, saasNeedRedundantAttrPoJo, purchaseEntityExt);
                        }
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PURCHASE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PRODUCTION_ORDER:
                        JSONObject productionOrderData = (JSONObject) paasFormDataEntity.getData().clone();
                        ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, productionOrderEntityExt);
                        // 关联产品特殊处理
                        JSONObject productionDataList = productionOrderEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(productionDataList, ProductionOrderEnum.PRODUCT.getAttr());
                        materiel = saasSaveHelp.formatSelectProduct4Save2(productionDataList, ProductionOrderEnum.MATERIEL.getAttr());
                        productionOrderEntityExt.setData(productionDataList);

                        productionOrderModel.insert(productionOrderEntityExt);
                        dataId = productionOrderEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setData(productionOrderData);
                        productionOrderData.put(ProductionOrderEnum.PRODUCT.getAttr(),productArray);
                        productionOrderData.put(ProductionOrderEnum.MATERIEL.getAttr(),materiel);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        productionOrderService.afterSave(saasFormSaveDTO);
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PRODUCTION_ORDER, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PAYMENT:
                    case RED_RECEIVABLES:
                        PaymentEntityExt paymentEntityExt = new PaymentEntityExt();
                        JSONObject paymentData = paasFormDataEntity.getData();
                        /*for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayment().entrySet()){
                            SaasDataInitHelp.antDataSet(paymentData,entry.getKey(),entry.getValue());
                        }*/
                        modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                        paasFormDataEntity.setSysLong10(modelType);
                        BeanUtil.copyProperties(paasFormDataEntity, paymentEntityExt);
                        paymentModel.insert(paymentEntityExt);
                        dataId = paymentEntityExt.getId();
                        JSONObject paymentDate=paymentEntityExt.getData();
                        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paymentDate,PaymentEnum.CUSTOMER.getAttr(),0L);
                        Long contractId = FastJsonHelper.getLongOrDefaultFromFormData(paymentDate,PaymentEnum.CONTRACT.getAttr(),0L);
                        userTeamService.createPaymentUser(corpid,customerId,contractId,Arrays.asList(dataId), PaymentLinkTypeEnum.CONTRACT.getCode(),false);

                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        afterSaveVO = paymentService.afterSave(saasFormSaveDTO);
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        logName = serialNo;
                        memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PaymentManage, operateTypeEnum,
                                paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        break;
                    case PAY_PLAN:
                        PayPlanEntityExt payPlanEntityExt = new PayPlanEntityExt();
                        JSONObject payPlanData = paasFormDataEntity.getData();
                        for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayPlan().entrySet()){
                            SaasDataInitHelp.antDataSet(payPlanData,entry.getKey(),entry.getValue());
                        }
                        BeanUtil.copyProperties(paasFormDataEntity, payPlanEntityExt);
                        payPlanModel.insert(payPlanEntityExt);
                        dataId = payPlanEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        payPlanService.afterSave(saasFormSaveDTO);

                        Long linkSupplierId = FastJsonHelper.getLongOrDefaultFromFormData(payPlanData,PayPlanEnum.LINK_SUPPLIER.getAttr(),0L);
                        Long linkPurchaseId = FastJsonHelper.getLongOrDefaultFromFormData(payPlanData,PayPlanEnum.LINK_PURCHASE.getAttr(),0L);
                        userTeamService.createPayPlanUser(corpid,linkSupplierId,linkPurchaseId,Arrays.asList(dataId),false);
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PayManage, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case INVOICE:
                        saasFormSaveDTO.setIsNew(true);
                        Long refundId = data.getLong(PaasConstant.REFUND_ID);
                        data.remove(PaasConstant.REFUND_ID);
                        data.remove(InvoiceEnum.UPDATE_TIME.getAttr());
                        modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                        paasFormDataEntity.setSysLong10(modelType);
                        InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, invoiceEntityExt);
                        invoiceModel.insert(invoiceEntityExt);
                        dataId = invoiceEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        JSONArray amountDetail = formDataAddDTO.getAmountDetail();
                        if(Objects.nonNull(amountDetail)){
                            saasFormSaveDTO.setAmountDetail(amountDetail);
                        }
                        invoiceService.afterSave(saasFormSaveDTO);
                        if(Objects.equals(saasFormSaveDTO.getHasReceivables(),BasicConstant.ONE)){
                            JSONObject hasReceivable = new JSONObject();
                            hasReceivable.put(BasicConstant.HASRECEIVABLES, I18nMessageUtil.getMessage(ErrorMessageConstant.RED_INVOICE_HAS_RECEIVABLES));
                            afterSaveVO.setSpecialMsg(hasReceivable);
                        }
                        if (refundId != null){
                            refundService.updateRefundInvoiceId(refundId, paasFormDataEntity, saasFormSaveDTO);
                        }
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.INVOICE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PURCHASE_INVOICE:
                        Long returnedPurchaseId = data.getLong(PaasConstant.RETURNED_PURCHASE_ID);
                        data.remove(PaasConstant.RETURNED_PURCHASE_ID);
                        PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = new PurchaseInvoiceEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity,purchaseInvoiceEntityExt);
                        purchaseInvoiceModel.insert(purchaseInvoiceEntityExt);
                        dataId = purchaseInvoiceEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        JSONArray purchaseInvoiceAmountDetail = formDataAddDTO.getAmountDetail();
                        if(Objects.nonNull(purchaseInvoiceAmountDetail)){
                            saasFormSaveDTO.setAmountDetail(purchaseInvoiceAmountDetail);
                        }
                        purchaseInvoiceService.afterSave(saasFormSaveDTO);
                        if (returnedPurchaseId != null) {
                            returnedPurchaseService.updateReturnedPurchaseInvoiceId(returnedPurchaseId, paasFormDataEntity, saasFormSaveDTO);
                        }
                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PURCHASE_INVOICE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case INVENTORY:
                        JSONObject inventoryData = (JSONObject) paasFormDataEntity.getData().clone();
                        InventoryEntityExt inventoryEntityExt = new InventoryEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, inventoryEntityExt);
                        // 关联产品特殊处理
                        JSONObject inventoryDataList = inventoryEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(inventoryDataList, InventoryEnum.PRODUCT.getAttr());
                        setDefaultData(redundantTemplateTypeEnum, inventoryDataList);
                        String inventoryType = FastJsonHelper.getStringOrDefaultFromFormData(inventoryDataList, InventoryEnum.INVENTORY_TYPE.getAttr(), InventoryTypeEnum.STANDARD_INVENTORY.getCode());
                        inventoryDataList.put(InventoryEnum.INVENTORY_TYPE.getAttr(), inventoryType);
                        inventoryEntityExt.setData(inventoryDataList);
                        inventoryModel.insert(inventoryEntityExt);
                        dataId = inventoryEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setData(inventoryData);
                        inventoryData.put(InventoryEnum.PRODUCT.getAttr(),productArray);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        inventoryService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.INVENTORY, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case TRANSFER:
                        JSONObject transferData = (JSONObject) paasFormDataEntity.getData().clone();
                        TransferEntityExt transferEntityExt = new TransferEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, transferEntityExt);
                        // 关联产品特殊处理
                        JSONObject transferDataList = transferEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(transferDataList, TransferEnum.PRODUCTS.getAttr());
                        // 设置默认值
                        String instockId = transferDataList.getString(TransferEnum.INSTOCK_ID.getAttr());
                        if (StringUtil.isEmpty(instockId)) {
                            transferDataList.put(TransferEnum.INSTOCK_ID.getAttr(), 0);
                        }
                        String outstockId = transferDataList.getString(TransferEnum.OUTSTOCK_ID.getAttr());
                        if (StringUtil.isEmpty(outstockId)) {
                            transferDataList.put(TransferEnum.OUTSTOCK_ID.getAttr(), 0);
                        }
                        String transferType = FastJsonHelper.getStringOrDefaultFromFormData(transferDataList, TransferEnum.TRANSFER_TYPE.getAttr(), TransferTypeEnum.UNLOCAL_TRANSFER.getCode());
                        transferDataList.put(TransferEnum.TRANSFER_TYPE.getAttr(), transferType);
                        transferData.put(TransferEnum.PRODUCTS.getAttr(),productArray);
                        transferEntityExt.setData(transferDataList);
                        transferModel.insert(transferEntityExt);
                        dataId = transferEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        paasFormDataEntity.setData(transferData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        transferService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.TRANSFER, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case WAREHOUSE:
                        WarehouseEntityExt warehouseEntityExt = new WarehouseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, warehouseEntityExt);
                        JSONObject dataListWahouse = warehouseEntityExt.getData();
                        setDefaultData(RedundantTemplateTypeEnum.WAREHOUSE, dataListWahouse);
                        warehouseModel.insert(warehouseEntityExt);
                        dataId = warehouseEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        warehouseService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
                            logName = name == null ? serialNo : sb.append(serialNo).append("（").append(name).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.WAREHOUSE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PRODUCT:
                        // 深拷贝出数据
                        JSONObject childData = (JSONObject) paasFormDataEntity.getData().clone();
                        ProductEntityExt productEntityExt = new ProductEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, productEntityExt);
                        JSONObject dataList = productEntityExt.getData();
                        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        List<StockNotifyPojo> stockNotifyList = productService.getSaveParam(dataList, supplierNameMap, warehouseNameMap);
                        productService.formatParentProduct4Save(dataList,corpid, productEntityExt);
                        // 父产品部分数据存入关联表，原数据置空
                        setDefaultData(RedundantTemplateTypeEnum.PRODUCT, dataList);
                        if (Objects.isNull(dataList.get(ProductEnum.COST.getAttr()))){
                            dataList.put(ProductEnum.COST.getAttr(),0);
                        }
                        productEntityExt.setData(dataList);
                        productEntityExt.setCost(dataList.getDouble(ProductEnum.COST.getAttr()));
                        productEntityExt.setTotalCost(0D);
                        productModel.insert(productEntityExt);
                        dataId = productEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        // 保存子产品
                        // 是否开启进销存
                        Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                        // 子产品部分数据存入关联表，原数据置空
                        productFormDataService.setProductDefaultData(childData);
                        paasFormDataEntity.setData(childData);
                        childData.put(ProductEnum.THUMBNAIL.getAttr(), dataList.get(ProductEnum.THUMBNAIL.getAttr()));
                        childData.put(ProductEnum.WAREHOUSE.getAttr(),dataList.getJSONArray(ProductEnum.WAREHOUSE.getAttr()));
                        childData.put(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr(),dataList.getJSONArray(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr()));
                        childData.put(ProductEnum.SUPPLIER.getAttr(),dataList.getJSONArray(ProductEnum.SUPPLIER.getAttr()));
                        childData.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(),dataList.getJSONArray(ProductEnum.SUPPLIER_LINK_TEXT.getAttr()));
                        FieldAttrEntity costField = formDataAddDTO.getExplainMap().get(ProductEnum.COST.getAttr());
                        Integer costAccuracy = Objects.isNull(costField) ? null : costField.getAccuracy();
                        ChildProductVO childProductVO = productService.saveChildProduct(saasFormSaveDTO.getNewPaasFormDataEntity(), isJxcUse, true, costAccuracy);

                        // 先保存供应商-产品信息，因为后面子产品的保存要对供应商字段做修改
                        if (isJxcUse) {
                            productService.associateWithSupplier(new ProductWithSupplierPojo(corpid, childProductVO, supplierNameMap, dataId));
                            ProductWithWarehousePojo productWithWarehousePojo = new ProductWithWarehousePojo(corpid, childProductVO, warehouseNameMap, dataId, stockNotifyList, false, dataList.getDouble(ProductEnum.COST.getAttr()));
                            BeanUtil.copyProperties(formDataAddDTO, productWithWarehousePojo);
                            if (Objects.nonNull(formDataAddDTO.getSaasNeedRedundantAttrPoJo())) {
                                productWithWarehousePojo.setProductWarehouseSavePojo(formDataAddDTO.getSaasNeedRedundantAttrPoJo().getProductWarehouseSavePojo());
                            }
                            productService.associateWithWarehouse(productWithWarehousePojo);
                        }
                        saasFormSaveDTO.setChildProductVO(childProductVO);
                        productService.afterSave(saasFormSaveDTO);

                        // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                        if(!isImport){
                            name = data.getString(ProductEnum.NAME.getAttr());
                            String productNo = FastJsonHelper.getStringOrDefaultFromFormData(data, ProductEnum.PRODUCT_NO.getAttr(), "");
                            logName = name == null ? productNo : sb.append(name).append("（").append(productNo).append("）").toString();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PRODUCT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case ASSEMBLE:
//                        JSONObject assembleData = (JSONObject) paasFormDataEntity.getData().clone();
                        AssembleEntityExt assembleEntityExt = new AssembleEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, assembleEntityExt);

                        // 关联产品特殊处理
                        JSONObject assembleDataList = assembleEntityExt.getData();
                        JSONArray outstockArray = saasSaveHelp.formatSelectProduct4Save2(assembleDataList, AssembleEnum.OUT_PRODUCTS.getAttr());
                        JSONArray instockArray = saasSaveHelp.formatSelectProduct4Save2(assembleDataList, AssembleEnum.IN_PRODUCTS.getAttr());
                        if (Objects.nonNull(creatorId)) {
                            Long outWarehouseId = FastJsonHelper.getLongOrDefaultFromFormData(assembleDataList, AssembleEnum.OUT_WAREHOUSE_ID.getAttr(), 0L);
                            assembleService.validateDataOutProduct(outstockArray,instockArray,saasFormSaveDTO.getCorpid(),outWarehouseId);
                        }
                        assembleEntityExt.setData(assembleDataList);
                        assembleModel.insert(assembleEntityExt);
                        dataId = assembleEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        assembleDataList.put(AssembleEnum.OUT_PRODUCTS.getAttr(),outstockArray);
                        assembleDataList.put(AssembleEnum.IN_PRODUCTS.getAttr(),instockArray);
                        paasFormDataEntity.setData(assembleDataList);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        assembleService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.ASSEMBLE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case INSTOCK:
                    case PURCHASE_INSTOCK:
                    case REFUND_INSTOCK:
                    case OTHER_INSTOCK:
                    case PRODUCTION_INSTOCK:
                    case RETURNED_MATERIEL_INSTOCK:
                        JSONObject instockData = (JSONObject) paasFormDataEntity.getData().clone();
                        InstockEntityExt instockEntityExt = new InstockEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, instockEntityExt);
                        // 关联产品特殊处理
                        JSONObject instockDataList = instockEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(instockDataList, InstockEnum.PRODUCT.getAttr());
                        instockEntityExt.setData(instockDataList);

                        instockModel.insert(instockEntityExt);
                        dataId = instockEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        // 保存入库单产品
                        saasFormSaveDTO.setIsNew(true);
                        instockData.put(InstockEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(instockData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);

                        instockService.afterSave(saasFormSaveDTO);

                        // 记录日志
                        if(!isImport){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, InstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum(), OperateTypeEnum.NEW,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case QUOTATION:
                        //copy骚逻辑(鉴于禹亮那边不能同步更新groupNumber,只能通过先去dataList中查看是否存在组号（单纯新建中没有）用于区分是复制新建还是单纯新建)
                        String groupNumber = formDataAddDTO.getGroupNumber();
                        JSONObject dataList1 = formDataAddDTO.getDataList();
                        Object object = dataList1.get(QuotationEnum.GROUP_NUMBER.getAttr());
                        //覆盖更新组号（cpoy的情况，前端无法更新）
                        if (object != null) {
                            groupNumber = Objects.toString(object, "");
                        }

                        JSONObject quotationData = (JSONObject) paasFormDataEntity.getData().clone();
                        QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, quotationEntityExt);
                        // 关联产品特殊处理
                        JSONObject quotationDataList = quotationEntityExt.getData();
                        JSONArray quotationProductArray = saasSaveHelp.formatSelectProduct4Save2(data, QuotationEnum.PRODUCT.getAttr());
                        quotationEntityExt.setData(quotationDataList);
                        // 新建的报价单，默认为最新版本
                        quotationModel.insert(quotationEntityExt);
                        dataId = quotationEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        saasFormSaveDTO.setIsNew(true);
                        paasFormDataEntity.getData().put(QuotationEnum.PRODUCT.getAttr(), quotationProductArray);
                        paasFormDataEntity.setData(quotationData);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        quotationService.afterSave(saasFormSaveDTO);

                        String version = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.VERSION.getAttr(), "");
                        Boolean newVersion = false;
                        if (!Objects.equals(version, StringConstant.DEFAULT_VERSION)) {
                            newVersion = true;
                        }
                        // 记录新建日志， 新版本的操作日志在afterSave里已经处理了
                        if(!isImport && !newVersion){
                            logName = serialNo;
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.QUOTATION, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PAYMENT_SHEET:
                    case BAD_DEBT:
                    case WRITE_OFF_PREPAYMENT:
                    case RED_PAYMENT_SHEET:
                    case RED_WRITE_OFF_PREPAYMENT:
                    case RED_WRITE_OFF_BALANCE:
                    case RED_PREPAYMENT:
                    case PREPAYMENT:
                        sheetFlag = true;
                        saasFormSaveDTO.setIsNew(true);
                        PaymentSheetEntityExt paymentSheetEntityExt = new PaymentSheetEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, paymentSheetEntityExt);
                        paymentSheetModel.insert(paymentSheetEntityExt);
                        //PaymentSheetSaveDTO paymentSheetSaveDTO = new PaymentSheetSaveDTO();
                        //BeanUtil.copyProperties(formDataAddDTO, paymentSheetSaveDTO);
                        //paymentSheetSaveDTO.setDataList(data);
                        //FormDataAddVO formDataAddVO = paymentSheetService.add(paymentSheetSaveDTO, paasFormDataEntity, paasFormEntityExt);
                        //BeanUtil.copyProperties(formDataAddVO, afterSaveVO);
                        dataId = paasFormDataEntity.getId();
                        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
                        paymentSheetService.afterSave(saasFormSaveDTO);
                        break;
                    case PAY_SHEET:
                    case PREPAY:
                    case WRITE_OFF_PREPAY:
                    case RED_WRITE_OFF_PAY:
                    case RED_WRITE_OFF_PREPAY:
                    case RED_PREPAY:
                    case BAD_PAY:
                        sheetFlag = true;
                        saasFormSaveDTO.setIsNew(true);
                        PayPlanSheetEntityExt payPlanSheetEntityExt = new PayPlanSheetEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, payPlanSheetEntityExt);
                        payPlanSheetModel.insert(payPlanSheetEntityExt);
                        dataId = paasFormDataEntity.getId();
                        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
                        payPlanSheetService.afterSave(saasFormSaveDTO);
                       /* sheetFlag = true;
                        PayPlanSheetInsertDTO payPlanSheetInsertDTO = new PayPlanSheetInsertDTO();
                        BeanUtil.copyProperties(formDataAddDTO, payPlanSheetInsertDTO);
                        payPlanSheetInsertDTO.setDataList(data);
                        formDataAddVO = payPlanSheetService.add(payPlanSheetInsertDTO, paasFormDataEntity, paasFormEntityExt);
                        BeanUtil.copyProperties(formDataAddVO, afterSaveVO);
                        dataId = paasFormDataEntity.getId();*/
                        break;
                    case MARKET_ACTIVITY:
                        MarketActivityEntityExt marketActivityEntityExt = new MarketActivityEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, marketActivityEntityExt);
                        marketActivityModel.insert(marketActivityEntityExt);
                        dataId = marketActivityEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        marketActivityService.afterSave(saasFormSaveDTO);
                        marketActivityForStaticHelp.addMarketActivity(paasFormDataEntity, xbbRefTypeEnum);
                        // }
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, MarketActivityEnum.NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.MARKET_ACTIVITY, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CLUE:
                        ClueEntityExt clueEntityExt = new ClueEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, clueEntityExt);
                        clueModel.insert(clueEntityExt);
                        dataId = clueEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        //没有addTime 和 updateTime 会导致评分不准
                        paasFormDataEntity.setAddTime(clueEntityExt.getAddTime());
                        paasFormDataEntity.setUpdateTime(clueEntityExt.getUpdateTime());
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        clueService.afterSave(saasFormSaveDTO);
                        marketActivityForStaticHelp.addMarketActivity(paasFormDataEntity, xbbRefTypeEnum);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.COMPANY_NAME.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CLUE, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case PAYMENT_TASK:
                        PaymentTaskEntityExt paymentTaskEntityExt = new PaymentTaskEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, paymentTaskEntityExt);
                        modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
                        paymentTaskEntityExt.setSysLong10(modelType);
                        paymentTaskModel.insert(paymentTaskEntityExt);
                        dataId = paymentTaskEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        //保存回款计划的后续操作
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        paymentTaskService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = paymentTaskEntityExt.getSerialNo();
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), paymentTaskEntityExt.getSerialNo());
//                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET, operateTypeEnum, paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CREDIT_LIMIT:
                        CreditLimitEntityExt creditEntityExt = new CreditLimitEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, creditEntityExt);
                        // 提取固定额度，给固定额度赋默认值0
                        Double fixedLimit = data.getDouble(CreditLimitEnum.FIXED_LIMIT.getAttr());
                        data.put(CreditLimitEnum.FIXED_LIMIT.getAttr(), 0);
                        creditLimitModel.insert(creditEntityExt);
                        dataId = creditEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        creditLimitService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CreditLimitEnum.CREDIT_NO.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_LIMIT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        // 固定额度处理
                        if (fixedLimit.compareTo(0D) > 0) {
                            FormDataAddDTO formDataSaveDTO = creditLimitService.setFixedFormDataAddDTO(saasFormSaveDTO, fixedLimit);
                            paasFormDataService.add(formDataSaveDTO);
                        }
                        break;
                    case CREDIT_TEMPORARY_LIMIT:
                        CreditTemporaryLimitEntityExt creditTemporaryEntityExt = new CreditTemporaryLimitEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, creditTemporaryEntityExt);
                        creditTemporaryLimitModel.insert(creditTemporaryEntityExt);
                        dataId = creditTemporaryEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        creditTemporaryLimitService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CreditTemporaryLimitEnum.CREDIT_TEMPORARY_NO.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_TEMPORARY_LIMIT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case CREDIT_FIXED_LIMIT:
                        CreditFixedLimitEntityExt creditFixedEntityExt = new CreditFixedLimitEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, creditFixedEntityExt);
                        creditFixedLimitModel.insert(creditFixedEntityExt);
                        dataId = creditFixedEntityExt.getId();
                        paasFormDataEntity.setId(dataId);
                        packageSaasFormInsertSaveDTO(saasFormSaveDTO, paasFormDataEntity);
                        creditFixedLimitService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        if(!isImport){
                            logName = FastJsonHelper.getStringOrDefaultFromFormData(data, CreditFixedLimitEnum.CREDIT_FIXED_NO.getAttr(), "");
                            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, xbbRefTypeEnum.getName(), logName);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CREDIT_FIXED_LIMIT, operateTypeEnum,
                                    paasFormDataEntity.getId().toString(), logName, memo, formDataAddDTO.getHttpHeader());
                        }
                        break;
                    case OTHER_INCOME:
                    case RED_OTHER_INCOME:
                        sheetFlag = true;
                        OtherIncomeSaveDTO otherIncomeSaveDTO = new OtherIncomeSaveDTO();
                        BeanUtil.copyProperties(formDataAddDTO, otherIncomeSaveDTO);
                        otherIncomeSaveDTO.setDataList(data);
                        formDataAddVO = otherIncomeService.add(otherIncomeSaveDTO, paasFormDataEntity, paasFormEntityExt);
                        BeanUtil.copyProperties(formDataAddVO, afterSaveVO);
                        dataId = paasFormDataEntity.getId();
                        break;
                    case OTHER_EXPENSE:
                    case RED_OTHER_EXPENSE:
                        sheetFlag = true;
                        OtherExpenseSaveDTO otherExpenseSaveDTO = new OtherExpenseSaveDTO();
                        BeanUtil.copyProperties(formDataAddDTO, otherExpenseSaveDTO);
                        otherExpenseSaveDTO.setDataList(data);
                        formDataAddVO = otherExpenseService.add(otherExpenseSaveDTO, paasFormDataEntity, paasFormEntityExt);
                        BeanUtil.copyProperties(formDataAddVO, afterSaveVO);
                        dataId = paasFormDataEntity.getId();
                        break;
                    default:
                        throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
                }
                //TODO   先判断是否有文件，再进行处理，不要进行不必要的循环   2019年7月11日14:49:57
                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataAddDTO.getExplainMap(), data, new JSONObject(), corpid, dataId, businessType, userId);
                //富文本保存
                richTextService.saveFormRichText(formDataAddDTO, paasFormDataEntity, richTextData);
            }
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            if (sheetFlag) {
                dataId = paasFormDataEntity.getId();
            }
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw e;
        } catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            if (sheetFlag) {
                dataId = paasFormDataEntity.getId();
            }
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }
        afterSaveVO.setFormDataId(dataId);
        return afterSaveVO;
    }

    /**
     * 新建竞争对手添加动态
     * @param saasFormSaveDTO
     */
    private void saveDynamic(SaasFormSaveDTO saasFormSaveDTO){

        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long dataId = newPaasFormDataEntity.getDataId();
        Long formId = newPaasFormDataEntity.getFormId();
        String corpid = newPaasFormDataEntity.getCorpid();
        String creatorId = newPaasFormDataEntity.getCreatorId();

        //竞争对手创建日志添加
        Runnable runnable = () -> {
            try {
                //获取用户信息
                UserEntity userEntity = userModel.getByKey(creatorId, corpid);

                DynamicStrategy dynamicStrategy = dynamicStrategyFactory.getDynamicStrategyByBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
                DynamicSaveDTO dynamicSaveDTO = DynamicSaveDTO.initDynamicSaveDTO(dataId, formId, saasFormSaveDTO, userEntity, null);
                dynamicStrategy.save(dynamicSaveDTO);
            }catch (Exception e){
                LOG.error("ProModelServiceImpl#saveDynamic exception :{}",e);
            }
        };

        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
    }

    @Override
    public void saveLinkPayPlan(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, PurchaseEntityExt purchaseEntityExt) throws XbbException {
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
            Long purchaseId = purchaseEntityExt.getId();
            PayPlanDTO payPlanDTO = new PayPlanDTO();
            payPlanDTO.setIsImport(saasFormSaveDTO.getIsImport());
            payPlanDTO.setParentNew(true);
            payPlanDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            payPlanDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), payPlanDTO);
            payPlanDTO.setBelonger(FastJsonHelper.getStringOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.SIGNER_ID.getAttr(),""));
            // TODO 审批过来的数据是最后审批人的userId
            payPlanDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());


            if (!payPlanDTO.getAddBatchList().isEmpty() && !Objects.equals(payPlanDTO.getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, payPlanDTO.getAddBatchList().size(), XbbRefTypeEnum.PAY_PLAN,
                        null);
                Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, payPlanDTO.getAddBatchList().size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            for (AddMuchFieldPojo addMuchFieldPojo : payPlanDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PayPlanEnum.LINK_PURCHASE.getAttr(), purchaseId.toString());
                addMuchFieldPojo.getData().put(PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(), purchaseEntityExt.getSerialNo());
            }
            payPlanService.payPlan(payPlanDTO);
        }
    }
    @Override
    public void saveLinkPayPlanSheet(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, PurchaseEntityExt purchaseEntityExt) throws XbbException {

        Double realPayTotalAmount = 0.0D;
        Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(purchaseEntityExt.getData(),PurchaseEnum.SUPPLIER_ID.getAttr(),0L);
        Long purchaseId = purchaseEntityExt.getId();
        PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
        payPlanSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
        payPlanSheetDTO.setParentNew(true);
        payPlanSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
        payPlanSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
        // TODO 审批过来的数据是最后审批人的userId
        payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());
        Integer flowStatus = paasFormDataEntity.getFlowStatus();
        List<AddMuchFieldPojo> writeOffPreSheets = new ArrayList<>();
        List<AddMuchFieldPojo> writeOffSheets = new ArrayList<>();

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            writeOffPreSheets = saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO().getAddBatchList();
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            writeOffSheets = saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO().getAddBatchList();
        }
        Integer count  = writeOffPreSheets.size() + writeOffSheets.size();
        if (!Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, count, XbbRefTypeEnum.PAY_PLAN,
                    null);
            Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, count);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }


        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            payPlanSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), payPlanSheetDTO);
            for (AddMuchFieldPojo addMuchFieldPojo : payPlanSheetDTO.getAddBatchList()) {
                if (Objects.equals(FlowStatusEnum.PASS.getType(), flowStatus)) {
                    //如果合同那边是经过审批的之后才走回款单这边逻辑，那么回款单不管进不进审批都不需要走团队成员校验
                    addMuchFieldPojo.setFromApproval(true);
                }
                addMuchFieldPojo.getData().put(PaySheetEnum.LINK_PURCHASE.getAttr(), Arrays.asList(purchaseId.toString()));
                addMuchFieldPojo.getData().put(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), Arrays.asList(purchaseEntityExt.getSerialNo()));
            }
            payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());
            PayPlanSheetAmountVO payPlanSheetAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO,PaySheetTypeEnum.WRITE_OFF_PREPAY,supplierId);
//            realPayTotalAmount = Arith.add(realPayTotalAmount, payPlanSheetAmountVO.getRealPayTotalAmount());
        }
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            payPlanSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), payPlanSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            payPlanSheetDTO.setProcessCreatorId(purchaseEntityExt.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : payPlanSheetDTO.getAddBatchList()) {
                if (Objects.equals(FlowStatusEnum.PASS.getType(), flowStatus)) {
                    //如果合同那边是经过审批的之后才走回款单这边逻辑，那么回款单不管进不进审批都不需要走团队成员校验
                    addMuchFieldPojo.setFromApproval(true);
                }
                addMuchFieldPojo.getData().put(PaySheetEnum.LINK_PURCHASE.getAttr(), Arrays.asList(purchaseId.toString()));
                addMuchFieldPojo.getData().put(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), Arrays.asList(purchaseEntityExt.getSerialNo()));
            }
            PayPlanSheetAmountVO payPlanSheetAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO,PaySheetTypeEnum.WRITE_OFF_PAY,supplierId);
//            realPayTotalAmount = Arith.add(realPayTotalAmount, payPlanSheetAmountVO.getRealPayTotalAmount());
        }
//        if ( realPayTotalAmount>0.0D ){
//            purchaseService.updateProfit(saasFormSaveDTO.getCorpid(),realPayTotalAmount,purchaseId,purchaseEntityExt);
//        }
    }

    @Override
    public void saveLinkPayment(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo) throws XbbException {
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
            Long contractId = paasFormDataEntity.getId();
            PaymentDTO paymentDTO = new PaymentDTO();
            paymentDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentDTO.setParentNew(true);
            paymentDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), paymentDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());

            if (!paymentDTO.getAddBatchList().isEmpty() && !Objects.equals(paymentDTO.getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, paymentDTO.getAddBatchList().size(), XbbRefTypeEnum.PAYMENT,
                        null);
                Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, paymentDTO.getAddBatchList().size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            for (AddMuchFieldPojo addMuchFieldPojo : paymentDTO.getAddBatchList()) {
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT.getAttr(), contractId.toString());
                addMuchFieldPojo.getData().put(PaymentEnum.CONTRACT_LINK_TEXT.getAttr(), paasFormDataEntity.getSerialNo());
            }
            paymentService.pay(paymentDTO);
        }
    }

    @Override
    public void saveLinkPaymentSheet(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo) throws XbbException {
        Double realPaymentTotalAmount = 0.0D;
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntity.getData(),ContractEnum.LINK_CUSTOMER.getAttr(),0L);
        Long contractId = paasFormDataEntity.getId();
        Integer flowStatus = paasFormDataEntity.getFlowStatus();
        boolean isWorkflowCompany = commonHelp.isOpenWorkFlow(saasFormSaveDTO.getCorpid());
        List<AddMuchFieldPojo> writeOffPreSheets = new ArrayList<>();
        List<AddMuchFieldPojo> writeOffSheets = new ArrayList<>();

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            writeOffPreSheets = saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO().getAddBatchList();
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            writeOffSheets = saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO().getAddBatchList();
        }
        Integer count  = writeOffPreSheets.size() + writeOffSheets.size();
        if (!Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, count, XbbRefTypeEnum.PAYMENT_SHEET,
                    null);
            Integer allStatus = packageStatusHelp.getPackageStatus(saasFormSaveDTO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, count);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }

        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                if (Objects.equals(FlowStatusEnum.PASS.getType(), flowStatus)) {
                    //如果合同那边是经过审批的之后才走回款单这边逻辑，那么回款单不管进不进审批都不需要走团队成员校验
                    addMuchFieldPojo.setFromApproval(true);
                }
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Arrays.asList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Arrays.asList(paasFormDataEntity.getSerialNo()));
            }
            //区分工作流公司
            if(isWorkflowCompany){
                paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
            }else {
                PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetService.addBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
                realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
            }
        }
        if (saasNeedRedundantAttrPoJo != null && saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null) {
            PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
            paymentSheetDTO.setOwnerId(saasFormSaveDTO.getOwnerId());
            paymentSheetDTO.setCoUserId(saasFormSaveDTO.getCoUserId());
            paymentSheetDTO.setIsImport(saasFormSaveDTO.getIsImport());
            paymentSheetDTO.setParentNew(true);
            paymentSheetDTO.setLinkContractEntity(paasFormDataEntity);
            BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
            // TODO 审批过来的数据是最后审批人的userId
            paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
            for (AddMuchFieldPojo addMuchFieldPojo : paymentSheetDTO.getAddBatchList()) {
                if (Objects.equals(FlowStatusEnum.PASS.getType(), flowStatus)) {
                    //如果合同那边是经过审批的之后才走回款单这边逻辑，那么回款单不管进不进审批都不需要走团队成员校验
                    addMuchFieldPojo.setFromApproval(true);
                }
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT.getAttr(), Arrays.asList(contractId.toString()));
                addMuchFieldPojo.getData().put(PaymentSheetEnum.CONTRACT_LINK_TEXT.getAttr(), Arrays.asList(paasFormDataEntity.getSerialNo()));
            }
            //区分工作流公司
            if(isWorkflowCompany){
                paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
            }else {
                PaymentSheetAmountVO writeOffAmountVO = paymentSheetService.addBatch(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
                Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
                realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
            }
        }
        /**
         * 处理合同的已收款金额，未收款金额，坏账金额
         * @author chenshan
         * @date 2019-11-30 12:56
         */
        if ( realPaymentTotalAmount>0.0D && !isWorkflowCompany ) {
            // 更新现金毛利
            contractService.updateCashProfit(saasFormSaveDTO.getCorpid(), realPaymentTotalAmount, contractId, paasFormDataEntity, saasFormSaveDTO.getDistributorMark());
        }
    }

    @Override
    public void setDefaultData(RedundantTemplateTypeEnum redundantTemplateTypeEnum, JSONObject dataList) {
        switch (redundantTemplateTypeEnum) {
            case PRODUCT:
                if (Objects.isNull(dataList.get(ProductEnum.COST.getAttr()))) {
                    dataList.put(ProductEnum.COST.getAttr(), 0.0);
                }
                if (Objects.isNull(dataList.get(ProductEnum.PRICE.getAttr()))) {
                    dataList.put(ProductEnum.PRICE.getAttr(), 0.0);
                }
                if (Objects.isNull(dataList.get(ProductEnum.STOCK.getAttr()))) {
                    dataList.put(ProductEnum.STOCK.getAttr(), 0.0);
                }
                if (Objects.isNull(dataList.get(ProductEnum.ONLINE_TIME.getAttr()))) {
                    dataList.put(ProductEnum.ONLINE_TIME.getAttr(), DateTimeUtil.getInt());
                }
                if (Objects.isNull(dataList.get(ProductEnum.SALES.getAttr()))) {
                    dataList.put(ProductEnum.SALES.getAttr(), 0.0);
                }
                if (Objects.nonNull(dataList.get(ProductEnum.STOCK_NOTIFY.getAttr()))) {
                    dataList.put(ProductEnum.STOCK_NOTIFY.getAttr(), null);
                }
                break;
            case INVENTORY:
                if (Objects.isNull(dataList.get(InventoryEnum.INSTOCK_ID.getAttr()))) {
                    dataList.put(InventoryEnum.INSTOCK_ID.getAttr(), 0);
                }
                if (Objects.isNull(dataList.get(InventoryEnum.OUTSTOCK_ID.getAttr()))) {
                    dataList.put(InventoryEnum.OUTSTOCK_ID.getAttr(), 0);
                }
                break;
            case WAREHOUSE:
                if (Objects.isNull(dataList.get(WarehouseEnum.ORI_STOCK.getAttr()))) {
                    dataList.put(WarehouseEnum.ORI_STOCK.getAttr(), WarehouseOriStockEnum.NOT_DONE.getCode());
                }
                break;
            default:
                break;
        }
    }

    /**
     * 避免代码冗余，提起数据封装
     *
     * @param saasFormSaveDTO    入参
     * @param paasFormDataEntity 数据实体
     * @date 2019/1/28 14:34
     */
    private void packageSaasFormInsertSaveDTO(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity) {
        saasFormSaveDTO.setIsNew(true);
        saasFormSaveDTO.setOldData(paasFormDataEntity.getData());
        saasFormSaveDTO.setNewData(paasFormDataEntity.getData());
        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
        saasFormSaveDTO.setOldPaasFormDataEntity(paasFormDataEntity);
    }

    /**
     * 更新保存后封装入参
     *
     * @param saasFormSaveDTO       保存实体后逻辑入参
     * @param paasFormDataEntity    新实体
     * @param oldPaasFormDataEntity 老实体
     * @author feng.zheng
     * @date 2019/1/30 10:19
     */
    private void packageSaasFormUpdateSaveDTO(SaasFormSaveDTO saasFormSaveDTO, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity) {
        paasFormDataEntity.setAddTime(oldPaasFormDataEntity.getAddTime());
        saasFormSaveDTO.setIsNew(false);
        saasFormSaveDTO.setOldPaasFormDataEntity(oldPaasFormDataEntity);
        saasFormSaveDTO.setNewPaasFormDataEntity(paasFormDataEntity);
        saasFormSaveDTO.setNewData(paasFormDataEntity.getData());
        saasFormSaveDTO.setOldData(oldPaasFormDataEntity.getData());
    }

    @Override
    @Deprecated
    public AfterSaveVO update(FormDataUpdateDTO formDataUpdateDTO, PaasFormDataEntity paasFormDataEntity, PaasFormDataEntity oldPaasFormDataEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        AfterSaveVO afterSaveVO = new AfterSaveVO();
        String corpid = formDataUpdateDTO.getCorpid();
        String userId = formDataUpdateDTO.getUserId();
        String creatorId = paasFormDataEntity.getCreatorId();
        String creatName = "";
        if(StringUtil.isNotEmpty(creatorId)){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            if (Objects.nonNull(user)) {
                creatName = user.getName();
            }
        }
        Integer distributorMark = paasFormEntityExt == null ? formDataUpdateDTO.getDistributorMark() : paasFormEntityExt.getDistributorMark();
        String userName = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatName : formDataUpdateDTO.getLoginUserName();
        userId = Objects.equals(paasFormDataEntity.getFlowStatus(), 2) ? creatorId : userId;
        Integer saasMark = formDataUpdateDTO.getSaasMark();
        boolean isCoverage = Objects.equals(1, formDataUpdateDTO.getIsImport());
        Integer businessType = formDataUpdateDTO.getBusinessType();
        //newObj放到switch内，是因为内部把paasFormDataEntity复制给了相应对象去保存，导致原paasFormDataEntity内部分字段与更新后的实体不一致，生成的日志不准确
        JSONObject newObj;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum;
        String opObjectName;
        OperateModuleTypeEnum operateModuleTypeEnum = null;
        JSONObject data = paasFormDataEntity.getData();
        FormDataUtil.removeSystemData(data);
        ReRollBackEntity reRollBackEntity = new ReRollBackEntity();
        try {
            int updateLine = 1;
            if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
                updateLine = paasFormDataModel.update(paasFormDataEntity);

                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataUpdateDTO.getExplainMap(), paasFormDataEntity.getData(), paasFormDataEntity.getSubFormData(), corpid, paasFormDataEntity.getId(), 0, userId);

                // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                // 解析标题
                Map<String, FieldAttrEntity> explainMap = formDataUpdateDTO.getExplainMap();
                List<FieldAttrEntity> list = new ArrayList<>();
                Iterator<String> iterator = explainMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String attr = iterator.next();
                    FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
                    list.add(fieldAttrEntity);
                }
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(paasFormDataEntity, paasFormDataEntityExt);
                String customTitle = Objects.isNull(paasFormEntityExt) ? null : paasFormEntityExt.getCustomTitle();
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(customTitle), explainMap, data, list, paasFormDataEntityExt);
                String title = "--";
                if(!formTitleList.isEmpty()){
                    formTitleList.forEach(titlePoJo->{
                        FieldAttrEntity fieldAttrEntity = explainMap.get(titlePoJo.getAttr());
                        if (Objects.nonNull(fieldAttrEntity) && ExplainUtil.isCombo(fieldAttrEntity.getFieldType())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(titlePoJo.getAttr(), titlePoJo.getValue());
                            Object value = ItemUtil.analysisComboReturnStr(jsonObject, fieldAttrEntity);
                            titlePoJo.setValue(Collections.singletonList(value));
                        }
                    });
                    title = TitleUtil.getTitle(formTitleList);
                }
                if(StringUtil.isEmpty(title)){
                    title = "--";
                }
                redundantTemplateTypeEnum = RedundantTemplateTypeEnum.PAAS;
                operateModuleTypeEnum = OperateModuleTypeEnum.PAAS_FORM_DATA;
                opObjectName = title;
                newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
            } else{
                if (businessType == null || businessType == 0) {
                    LOG.error("businessType为空");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                BeanUtil.copyProperties(formDataUpdateDTO, saasFormSaveDTO);
                saasFormSaveDTO.setBusinessType(businessType);
                redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);

                Long dataId = paasFormDataEntity.getId();
                JSONObject oldData = oldPaasFormDataEntity.getData();
                String serialNo = paasFormDataEntity.getSerialNo();
                List<ValidateDataDTO> needAddValidateDataDTO = null;
                List<ValidateDataDTO> needDelValidateDataDTO = null;
                List<ValidateDataDTO> needUpdateValidateDataDTO = null;
                StringBuilder sb = new StringBuilder();
                switch (redundantTemplateTypeEnum) {
                    case CUSTOMER:
                        //TODO 剔除联系人
                        String oldCustomerName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, CustomerManagementEnum.NAME.getAttr(), "");
                        Long oldLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(oldData, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                        data = paasFormDataEntity.getData();
                        Long newLastConnectTime = FastJsonHelper.getLongOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), 0L);
                        opObjectName = data.getString(CustomerManagementEnum.NAME.getAttr());
                        data.remove(CustomerManagementEnum.ADD_CONTACT.getAttr());
                        if ( oldLastConnectTime > newLastConnectTime ) {
                            data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(),oldLastConnectTime);
                        }
                        paasFormDataEntity.setData(data);
                        CustomerEntityExt customerEntityExt = new CustomerEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, customerEntityExt);
                        updateLine = customerModel.update(customerEntityExt);
                        paasFormDataEntity.setUpdateTime(customerEntityExt.getUpdateTime());
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        customerService.afterSave(saasFormSaveDTO);
                        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();

                        if (saasNeedRedundantAttrPoJo != null) {
                            needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
                            needDelValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedDelValidateDataDTO();
                            needUpdateValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedUpdateValidateDataDTO();
                        }
                        if (!Objects.isNull(needAddValidateDataDTO) || !Objects.isNull(needDelValidateDataDTO) || !Objects.isNull(needUpdateValidateDataDTO)) {
                            paasFormDataHelper.batchEditContactForUpdate(saasNeedRedundantAttrPoJo, formDataUpdateDTO.getLoginUser(), formDataUpdateDTO.getProcessCreatorId(), corpid, dataId, opObjectName, formDataUpdateDTO.getIsImport(), ContactEnum.CUSTOMER_NAME.getAttr(), XbbRefTypeEnum.CONTACT);
                        }

                        // 客户数据一致性同步
                        if (!Objects.equals(oldCustomerName, opObjectName)) {
                            LOG.info("customer update customer name : corpid= " + corpid + ">dataId=" + dataId + ">newName="+ opObjectName + ">oldName="+ oldCustomerName);
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(customerEntityExt.getCorpid(), customerEntityExt.getId(), opObjectName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CUSTOMER);
                        }

                        // 记录日志
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(customerEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CUSTOMER;
                        break;
                    case CONTRACT:
                        opObjectName = data.getString(ContractEnum.NAME.getAttr());
                        String oldContractSerialNo = oldPaasFormDataEntity.getSerialNo();
                        data = paasFormDataEntity.getData();
                        String newContractSerialNo = paasFormDataEntity.getSerialNo();
                        data.remove(ContractEnum.ADD_PAYMENT.getAttr());
                        data.remove(ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                        data.remove(ContractEnum.ADD_PAYMENT_SHEET.getAttr());
                        paasFormDataEntity.setData(data);
                        ContractEntityExt contractEntityExt = new ContractEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, contractEntityExt);
                        // 关联产品特殊处理
                        JSONObject conDataList = contractEntityExt.getData();
                        JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conDataList, ContractEnum.PRODUCT.getAttr());
                        contractEntityExt.setData(conDataList);

                        updateLine = contractModel.update(contractEntityExt);
                        contractEntityExt.getData().put(ContractEnum.PRODUCT.getAttr(),productArray);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);

                        // 保存合同后的操作
                        contractService.afterSave(saasFormSaveDTO);

                        saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();
                        PaymentDTO paymentDTO = new PaymentDTO();
                        if (saasNeedRedundantAttrPoJo != null ) {
                            Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(contractEntityExt.getData(), ContractEnum.LINK_CUSTOMER.getAttr(), 0L);
                            if ( saasNeedRedundantAttrPoJo.getAddBatchDTO() != null ) {
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), paymentDTO);
                                paymentDTO.setIsImport(formDataUpdateDTO.getIsImport());
                                if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                                    paymentDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                                }
                                paymentService.pay(paymentDTO);
                            }
                            Double realPaymentTotalAmount = 0.0D;
                            if ( saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null ) {
                                PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), paymentSheetDTO);
                                paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                                PaymentSheetAmountVO writeOffPrepaymentAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT, customerId);
                                realPaymentTotalAmount = writeOffPrepaymentAmountVO.getRealPaymentTotalAmount();
                            }
                            if ( saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null ) {
                                PaymentSheetDTO paymentSheetDTO = new PaymentSheetDTO();
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), paymentSheetDTO);
                                paymentSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                                PaymentSheetAmountVO writeOffAmountVO = paymentSheetService.addBatchForWorkflow(paymentSheetDTO, PaymentSheetTypeEnum.WRITE_OFF, customerId);
                                Double addPaymentAmount = writeOffAmountVO.getRealPaymentTotalAmount();
                                realPaymentTotalAmount = Arith.add(realPaymentTotalAmount, addPaymentAmount);
                            }
                            /**
                             * 处理合同的已回款金额和未收款金额，坏账金额
                             * @author chenshan
                             * @date 2019-11-30 12:47
                             */
                            if ( realPaymentTotalAmount>0.0D ) {
                                // 更新现金毛利
                                contractService.updateCashProfit(saasFormSaveDTO.getCorpid(), realPaymentTotalAmount, contractEntityExt.getId(), contractEntityExt, paasFormEntityExt.getDistributorMark());
                            }
                        }

                        if (!Objects.equals(oldContractSerialNo, newContractSerialNo)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(contractEntityExt.getCorpid(), contractEntityExt.getId(), newContractSerialNo, newContractSerialNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTRACT);
                        }
                        // 记录日志
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(contractEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CONTRACT;
                        break;
                    case CONTACT:
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, ContactEnum.NAME.getAttr(), "");
                        JSONObject newData = paasFormDataEntity.getData();
                        String newContactName = newData.getString(ContactEnum.NAME.getAttr());
                        Object customerInfo = newData.get(ContactEnum.CUSTOMER_NAME.getAttr());
                        if (Objects.nonNull(customerInfo) && customerInfo instanceof JSONArray) {
                            JSONObject customerJson = ((JSONArray)customerInfo).getJSONObject(BasicConstant.ZERO);
                            Long customerId = customerJson.getLong(BasicConstant.ID);
                            newData.put(ContactEnum.CUSTOMER_NAME.getAttr(), customerId);
                        }
                        ContactEntityExt contactEntityExt = new ContactEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, contactEntityExt);
                        updateLine = contactModel.update(contactEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        contactService.afterSave(saasFormSaveDTO);

                        if (!Objects.equals(opObjectName, newContactName)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(contactEntityExt.getCorpid(), contactEntityExt.getId(), newContactName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CONTACT);
                        }
                        // 记录日志
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(contactEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CONTACT;
                        break;
                    case SALES_OPPORTUNITY:
                        String oldOpportunitySerialNo = oldPaasFormDataEntity.getSerialNo();
                        OpportunityEntityExt opportunityEntity = new OpportunityEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, opportunityEntity);
                        // 关联产品特殊处理
                        JSONObject oppDataList = opportunityEntity.getData();
                        String newOpportunitySerialNo = opportunityEntity.getSerialNo();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(oppDataList, SalesOpportunityEnum.PRODUCTS.getAttr());
                        opportunityEntity.setData(oppDataList);

                        updateLine = opportunityModel.update(opportunityEntity);
                        paasFormDataEntity.getData().put(SalesOpportunityEnum.PRODUCTS.getAttr(),productArray);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        opportunityService.afterSave(saasFormSaveDTO);

                        if (!Objects.equals(oldOpportunitySerialNo, newOpportunitySerialNo)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(opportunityEntity.getCorpid(), opportunityEntity.getId(), "", newOpportunitySerialNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.SALES_OPPORTUNITY);
                        }
                        marketActivityForStaticHelp.updateMarketActivity(paasFormDataEntity,redundantTemplateTypeEnum);
                        // 记录日志
                        opObjectName = data.getString(SalesOpportunityEnum.NAME.getAttr());
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(opportunityEntity));
                        operateModuleTypeEnum = OperateModuleTypeEnum.OPPORTUNITY;
                        break;
                    case BOMBILL:
                        JSONObject bomBillData = (JSONObject) paasFormDataEntity.getData().clone();
                        BomBillEntityExt bomBillEntityExt = new BomBillEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, bomBillEntityExt);
                        // 关联产品特殊处理
                        JSONObject bomDataList = bomBillEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(bomDataList, BomBillEnum.PRODUCT.getAttr());
                        JSONArray materiel = saasSaveHelp.formatSelectProduct4Save2(bomDataList, BomBillEnum.MATERIEL.getAttr());
                        bomBillEntityExt.setData(bomDataList);

                        updateLine = bomBillModel.update(bomBillEntityExt);
                        bomBillData.put(BomBillEnum.PRODUCT.getAttr(),productArray);
                        bomBillData.put(BomBillEnum.MATERIEL.getAttr(),materiel);
                        paasFormDataEntity.setData(bomBillData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        bomBillService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = data.getString(BomBillEnum.NAME.getAttr());
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(bomBillEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.BOMBILL;
                        break;
                    case COMMUNICATE_PLAN:
                        CommunicatePlanEntityExt communicatePlanEntityExt = new CommunicatePlanEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, communicatePlanEntityExt);
                        updateLine = communicatePlanModel.update(communicatePlanEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        communicatePlanService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicatePlanEnum.NAME.getAttr(), "");
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(communicatePlanEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CommunicatePlan;
                        break;
                    case WORKREPORT_DAILY:
                    case WORKREPORT_WEEKLY:
                    case WORKREPORT_MONTHLY:
                    case WORKREPORT:
                        WorkReportEntityExt workReportEntityExt = new WorkReportEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, workReportEntityExt);
                        workReportModel.update(workReportEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        workReportService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        JSONObject workReportData = saasFormSaveDTO.getNewPaasFormDataEntity().getData();
                        Long reportDate = FastJsonHelper.getLongOrDefaultFromFormData(workReportData, WorkReportFieldEnum.REPORT_DATE.getAttr(), 0L);
                        String reportSec = DateTimeUtil.getStringEpochSecond(reportDate, DateTimeUtil.SDFDate);
                        RedundantTemplateTypeEnum workReportTypeEnum = RedundantTemplateTypeEnum.getByCode(formDataUpdateDTO.getSubBusinessType());
                        opObjectName = "";
                        switch (workReportTypeEnum) {
                            case WORKREPORT_DAILY:
                                opObjectName = "日报(“" + reportSec + "“)";
                                break;
                            case WORKREPORT_WEEKLY:
                                opObjectName = "周报(“" + reportSec + "“)";
                                break;
                            case WORKREPORT_MONTHLY:
                                opObjectName = "月报(“" + reportSec + "“)";
                                break;
                            default:
                                break;
                        }
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(workReportEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.WORKREPORT;
                        break;
                    case COMMUNICATE:
                        CustomerCommunicateEntityExt customerCommunicateEntityExt = new CustomerCommunicateEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, customerCommunicateEntityExt);
                        updateLine = customerCommunicateModel.update(customerCommunicateEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        customerCommunicateService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(customerCommunicateEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CustomerCommunicate;
                        break;
                    case JXC_COMMUNICATE:
                        SupplierCommunicateEntityExt supplierCommunicateEntityExt = new SupplierCommunicateEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierCommunicateEntityExt);
                        updateLine = supplierCommunicateModel.update(supplierCommunicateEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        supplierCommunicateService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), "");
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(supplierCommunicateEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.SUPPLIER_COMMUNICATE;
                        break;
                    case SUPPLIER:
                        JSONObject supplierData = (JSONObject) paasFormDataEntity.getData().clone();
                        SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierEntityExt);
                        // 关联产品特殊处理
                        JSONObject supplierDataList = supplierEntityExt.getData();
                        // 不做保存了，此字段仅作为表单冗余字段
                        //saasSaveHelp.formatSelectProduct4Save(productList, SupplierEnum.PRODUCT_LIST.getAttr());
                        supplierDataList.remove(SupplierEnum.PRODUCT_LIST.getAttr());
                        supplierDataList.remove(SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr());
                        supplierEntityExt.setData(supplierDataList);

                        updateLine = supplierModel.update(supplierEntityExt);
                        saasFormSaveDTO.setIsNew(false);
                        paasFormDataEntity.setData(supplierData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        supplierService.afterSave(saasFormSaveDTO);
                        SaasNeedRedundantAttrPojo needRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();
                        if (needRedundantAttrPoJo != null) {
                            needAddValidateDataDTO = needRedundantAttrPoJo.getNeedAddValidateDataDTO();
                            needDelValidateDataDTO = needRedundantAttrPoJo.getNeedDelValidateDataDTO();
                            needUpdateValidateDataDTO = needRedundantAttrPoJo.getNeedUpdateValidateDataDTO();
                        }
                        opObjectName = supplierData.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                        if (!Objects.isNull(needAddValidateDataDTO) || !Objects.isNull(needDelValidateDataDTO) || !Objects.isNull(needUpdateValidateDataDTO)) {
                            paasFormDataHelper.batchEditContactForUpdate(needRedundantAttrPoJo, formDataUpdateDTO.getLoginUser(), formDataUpdateDTO.getProcessCreatorId(), corpid, formDataUpdateDTO.getDataId(), paasFormDataEntity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr()), formDataUpdateDTO.getIsImport(), SupplierContactEnum.SUPPLIER_ID.getAttr(), XbbRefTypeEnum.SUPPLIER_CONTACT);
                        }

                        // 数据一致性同步
                        String oldSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, SupplierEnum.SUPPLIER_NAME.getAttr(), "");

                        if (!Objects.equals(oldSupplierName, opObjectName)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), opObjectName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.SUPPLIER);
                        }
                        // 记录日志
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(supplierEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.SUPPLIER;
                        break;
                    case SUPPLIER_CONTACT:
                        JSONObject supplierContactData = (JSONObject) paasFormDataEntity.getData().clone();
                        SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, supplierContactEntityExt);
                        Object supplierContactInfo = supplierContactEntityExt.getData().get(SupplierContactEnum.SUPPLIER_ID.getAttr());
                        if (Objects.nonNull(supplierContactInfo) && supplierContactInfo instanceof JSONArray) {
                            JSONObject supplierJson = ((JSONArray)supplierContactInfo).getJSONObject(BasicConstant.ZERO);
                            Long supplierId = supplierJson.getLong(BasicConstant.ID);
                            supplierContactEntityExt.getData().put(SupplierContactEnum.SUPPLIER_ID.getAttr(), supplierId);
                        }else if (Objects.nonNull(supplierContactInfo) && supplierContactInfo instanceof String) {
                            supplierContactEntityExt.getData().put(SupplierContactEnum.SUPPLIER_ID.getAttr(), Long.parseLong((String)supplierContactInfo));
                        }
                        updateLine = supplierContactModel.update(supplierContactEntityExt);
                        saasFormSaveDTO.setIsNew(false);
                        paasFormDataEntity.setData(supplierContactData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        supplierContactService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.NAME.getAttr(), "");
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(supplierContactEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.SUPPLIER_CONTACT;
                        break;
                    case PURCHASE:
                        JSONObject purchaseData = (JSONObject) paasFormDataEntity.getData().clone();
                        data = paasFormDataEntity.getData();
                        data.remove(PurchaseEnum.ADD_PAYPLAN.getAttr());
                        data.remove(PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr());
                        data.remove(PurchaseEnum.ADD_PAY_SHEET.getAttr());
                        paasFormDataEntity.setData(data);
                        PurchaseEntityExt purchaseEntityExt = new PurchaseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, purchaseEntityExt);
                        // 关联产品特殊处理
                        JSONObject purchaseDataList = purchaseEntityExt.getData();
                        // 在插入之前对产品数据进行校验
//                        purchaseService.checkPurchaseProduct(purchaseDataList, true, purchaseEntityExt.getCorpid(), purchaseEntityExt.getId());
                        productArray = saasSaveHelp.formatSelectProduct4Save2(purchaseDataList, PurchaseEnum.PRODUCT.getAttr());
                        // 判断关联产品字段是否可见
                       /* HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                        BeanUtil.copyProperties(formDataUpdateDTO, handlerExplainDTO);
                        boolean productCansee = commonHelp.attrCanSee(PurchaseEnum.PRODUCT.getAttr(), formDataUpdateDTO.getExplainMap(), handlerExplainDTO);
                        if(productCansee){
                            purchaseService.checkPurchaseProduct(purchaseDataList, true, purchaseEntityExt.getCorpid(), purchaseEntityExt.getId(), productCansee);
                            saasSaveHelp.formatSelectProduct4Save(purchaseDataList, PurchaseEnum.PRODUCT.getAttr());
                        } else {
                            JSONArray oldProductArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(oldData, PurchaseEnum.PRODUCT.getAttr(), new JSONArray());
                            purchaseDataList.put(PurchaseEnum.PRODUCT.getAttr(), oldProductArray);
                        }*/
                        purchaseEntityExt.setData(purchaseDataList);

                        updateLine = purchaseModel.update(purchaseEntityExt);
                        saasFormSaveDTO.setIsNew(false);
                        purchaseData.put(PurchaseEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(purchaseData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        purchaseService.afterSave(saasFormSaveDTO);
                        saasNeedRedundantAttrPoJo = formDataUpdateDTO.getSaasNeedRedundantAttrPoJo();
                        if ( saasNeedRedundantAttrPoJo != null ) {
                            Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(purchaseEntityExt.getData(), PurchaseEnum.SUPPLIER_ID.getAttr(), 0L);
                            if ( saasNeedRedundantAttrPoJo.getAddBatchDTO() != null) {
                                PayPlanDTO payPlanDTO = new PayPlanDTO();
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddBatchDTO(), payPlanDTO);
                                payPlanDTO.setIsImport(formDataUpdateDTO.getIsImport());
                                payPlanDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                                payPlanService.payPlan(payPlanDTO);
                            }
                            Double realPayPlanTotalAmount = 0.0D;
                            if ( saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO() != null ) {
                                PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddWriteOffPrepaymentBatchDTO(), payPlanSheetDTO);
                                PayPlanSheetAmountVO writeOffPrepaymentAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO, PaySheetTypeEnum.WRITE_OFF_PREPAY, supplierId);
                                realPayPlanTotalAmount = writeOffPrepaymentAmountVO.getRealPayTotalAmount();
                            }
                            if ( saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO() != null ) {
                                PayPlanSheetDTO payPlanSheetDTO = new PayPlanSheetDTO();
                                BeanUtil.copyProperties(saasNeedRedundantAttrPoJo.getAddPaymentSheetBatchDTO(), payPlanSheetDTO);
                                if (Objects.nonNull(formDataUpdateDTO.getIsFromProcess()) && Objects.equals(formDataUpdateDTO.getIsFromProcess(), 1)) {
                                    payPlanSheetDTO.setProcessCreatorId(paasFormDataEntity.getCreatorId());
                                }
                                PayPlanSheetAmountVO writeOffAmountVO = payPlanSheetService.addBatchForWorkflow(payPlanSheetDTO, PaySheetTypeEnum.WRITE_OFF_PAY, supplierId);
                                Double addPaymentAmount = writeOffAmountVO.getRealPayTotalAmount();
                                realPayPlanTotalAmount = Arith.add(realPayPlanTotalAmount, addPaymentAmount);
                            }
                            //todo chenshan2
                            if ( realPayPlanTotalAmount>0.0D ) {
                                purchaseService.updateProfit(saasFormSaveDTO.getCorpid(), realPayPlanTotalAmount, purchaseEntityExt.getId(), purchaseEntityExt);
                            }
                        }
                        // 记录日志
                        opObjectName = data.getString(PurchaseEnum.PURCHASE_NAME.getAttr());
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        // 采购合同编号数据一致性同步
                        String oldSeriNo = oldPaasFormDataEntity.getSerialNo();
                        if (!Objects.equals(oldSeriNo, serialNo)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(purchaseEntityExt.getCorpid(), purchaseEntityExt.getId(), serialNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PURCHASE);
                        }
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(purchaseEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PURCHASE;
                        break;
                    case RETURNED_PURCHASE:
                        JSONObject returnedPurchaseData = (JSONObject) paasFormDataEntity.getData().clone();
                        ReturnedPurchaseEntityExt returnedPurchaseEntityExt = new ReturnedPurchaseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, returnedPurchaseEntityExt);
                        // 关联产品特殊处理
                        JSONObject returnedPurchaseDataList = returnedPurchaseEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(returnedPurchaseDataList, ReturnedPurchaseEnum.PRODUCTS.getAttr());
                        //关联付款单发票字段处理
                        JSONArray purchaseInvoiceArray = returnedPurchaseData.getJSONArray(ReturnedPurchaseEnum.INVOICES.getAttr());
                        JSONArray paySheetArray = returnedPurchaseData.getJSONArray(ReturnedPurchaseEnum.PAY_SHEETS.getAttr());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnedPurchaseEnum.INVOICES.getAttr(), ReturnedPurchaseEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.INVOICES.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getFieldType());
                        //合计退款金额在afterSave中处理，根据回款单是否创建成功来处理
                        Double returnedPurchaseAmount = getDoubleOrDefaultFromFormData(data, ReturnedPurchaseEnum.RETURNED_PURCHASE_AMOUNT.getAttr(), 0D);
                        returnedPurchaseEntityExt.setData(returnedPurchaseDataList);
                        PaasFormEntity paySheetFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PAY_SHEET.getCode(), corpid);
                        PaasFormEntity purchaseInvoiceFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), corpid);
                        boolean isPaySheetIsProcess = Objects.equals(paySheetFormEntity.getIsProcessForm(), BasicConstant.ONE);
                        boolean isPurchaseInvoiceIsProcess = Objects.equals(purchaseInvoiceFormEntity.getIsProcessForm(), BasicConstant.ONE);
                        updateLine = returnedPurchaseModel.update(returnedPurchaseEntityExt);
                        saasFormSaveDTO.setIsNew(false);
                        returnedPurchaseData.put(ReturnedPurchaseEnum.PRODUCTS.getAttr(),productArray);
                        paasFormDataEntity.setData(returnedPurchaseData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        AssociatedBusinessAfterSavePojo associatedBusinessAfterSavePojo = new AssociatedBusinessAfterSavePojo(purchaseInvoiceArray, paySheetArray, null, returnedPurchaseAmount, reRollBackEntity, isPaySheetIsProcess, isPurchaseInvoiceIsProcess);
                        returnedPurchaseService.afterSave(saasFormSaveDTO, returnedPurchaseEntityExt, associatedBusinessAfterSavePojo);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(returnedPurchaseEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.RETURN_PURCHASE;
                        break;
                    case PRODUCTIONORDER:
                        JSONObject productionOrderData = (JSONObject) paasFormDataEntity.getData().clone();
                        ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, productionOrderEntityExt);
                        // 关联产品特殊处理
                        JSONObject proDataList = productionOrderEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(proDataList, ProductionOrderEnum.PRODUCT.getAttr());
                        materiel = saasSaveHelp.formatSelectProduct4Save2(proDataList, ProductionOrderEnum.MATERIEL.getAttr());
                        updateLine = productionOrderModel.update(productionOrderEntityExt);
                        proDataList.put(ProductionOrderEnum.PRODUCT.getAttr(),productArray);
                        proDataList.put(ProductionOrderEnum.MATERIEL.getAttr(),materiel);
                        productionOrderEntityExt.setData(proDataList);
                        paasFormDataEntity.setData(productionOrderData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        productionOrderService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(productionOrderEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PRODUCTION_ORDER;
                        break;
                    case PAYMENT:
                        PaymentStatusEnum paymentStatusEnum = PaymentStatusEnum.getByCode(oldData.getString(PaymentEnum.STATUS.getAttr()));
                        //得到编辑时禁止修改的字段list：应收款编辑是，部分特定字段不允许修改，值必须用原值
                        List<String> paymentUnableEditAttrList = PaymentBaseEnum.getUnableEditAttrList(paymentStatusEnum);
                        for (String attr : paymentUnableEditAttrList) {
                            data.put(attr, oldData.get(attr));
                        }
                        paasFormDataEntity.setData(data);
                        PaymentEntityExt paymentEntityExt = new PaymentEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, paymentEntityExt);
                        updateLine = paymentModel.update(paymentEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        afterSaveVO = paymentService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                        paymentEntityExt.setOwnerId(null);
                        paymentEntityExt.setDepartmentId(null);
                        // 应收款编号数据一致性同步 目前只有销项发票需要同步
                        String oldPaymentSeriNo = oldPaasFormDataEntity.getSerialNo();
                        if (!Objects.equals(oldPaymentSeriNo, serialNo)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paymentEntityExt.getCorpid(), paymentEntityExt.getId(), serialNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PAYMENT);
                        }
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                        break;
                    case PAY_PLAN:
                        PayPlanStatusEnum payStatusEnum = PayPlanStatusEnum.getByCode(oldData.getString(PayPlanEnum.STATUS.getAttr()));
                        //得到编辑时禁止修改的字段list：付款计划编辑是，部分特定字段不允许修改，值必须用原值
                        List<String> payUnableEditAttrList = PayPlanEnum.getUnableEditAttrList(true, payStatusEnum);
                        for (String attr : payUnableEditAttrList) {
                            data.put(attr, oldData.get(attr));
                        }
                        paasFormDataEntity.setData(data);
                        PayPlanEntityExt payPlanEntityExt = new PayPlanEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, payPlanEntityExt);
                        updateLine = payPlanModel.update(payPlanEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        payPlanService.afterSave(saasFormSaveDTO);
                        // 付款计划编号数据一致性同步 目前只有销项发票需要同步
                        String oldPayPlanSeriNo = oldPaasFormDataEntity.getSerialNo();
                        if (!Objects.equals(oldPayPlanSeriNo, serialNo)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(payPlanEntityExt.getCorpid(), payPlanEntityExt.getId(), serialNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PAY_PLAN);
                        }
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(payPlanEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PayManage;
                        break;
                    case INVOICE:
                        invoiceCommonHelper.checkApiResultSafe(paasFormDataEntity);
                        InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, invoiceEntityExt);
                        updateLine = invoiceModel.update(invoiceEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        invoiceService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(invoiceEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.INVOICE;
                        break;
                    case PURCHASE_INVOICE:
                        invoiceCommonHelper.checkApiResultSafe(paasFormDataEntity);
                        PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = new PurchaseInvoiceEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity,purchaseInvoiceEntityExt);
                        updateLine = purchaseInvoiceModel.update(purchaseInvoiceEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO,paasFormDataEntity,oldPaasFormDataEntity);
                        purchaseInvoiceService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(purchaseInvoiceEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PURCHASE_INVOICE;
                        break;
                    case INVENTORY:
                        JSONObject inventoryData = (JSONObject) paasFormDataEntity.getData().clone();
                        InventoryEntityExt inventoryEntityExt = new InventoryEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, inventoryEntityExt);
                        // 关联产品特殊处理
                        JSONObject inventoryDataList = inventoryEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(inventoryDataList, InventoryEnum.PRODUCT.getAttr());
                        inventoryEntityExt.setData(inventoryDataList);
                        updateLine = inventoryModel.update(inventoryEntityExt);
                        inventoryData.put(InventoryEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(inventoryData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        inventoryService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(inventoryEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.INVENTORY;
                        break;
                    case TRANSFER:
                        JSONObject transferData = (JSONObject) paasFormDataEntity.getData().clone();
                        TransferEntityExt transferEntityExt = new TransferEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, transferEntityExt);
                        // 关联产品特殊处理
                        JSONObject transferDataList = transferEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(transferDataList, TransferEnum.PRODUCTS.getAttr());
                        // 设置默认值
                        String instockId = transferDataList.getString(TransferEnum.INSTOCK_ID.getAttr());
                        if (StringUtil.isEmpty(instockId)) {
                            transferDataList.put(TransferEnum.INSTOCK_ID.getAttr(), 0);
                        }
                        String outstockId = transferDataList.getString(TransferEnum.OUTSTOCK_ID.getAttr());
                        if (StringUtil.isEmpty(outstockId)) {
                            transferDataList.put(TransferEnum.OUTSTOCK_ID.getAttr(), 0);
                        }
                        updateLine = transferModel.update(transferEntityExt);
                        transferDataList.put(TransferEnum.PRODUCTS.getAttr(),productArray);
                        transferEntityExt.setData(transferDataList);
                        paasFormDataEntity.setData(transferData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        transferService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(transferEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.TRANSFER;
                        break;
                    case WAREHOUSE:
                        WarehouseEntityExt warehouseEntityExt = new WarehouseEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, warehouseEntityExt);
                        updateLine = warehouseModel.update(warehouseEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        warehouseService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = data.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
                        String newWarehouseName = opObjectName;
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        //仓库不更新ownerId
                        warehouseEntityExt.setOwnerId(oldPaasFormDataEntity.getOwnerId());
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(warehouseEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.WAREHOUSE;

                        //仓库名称一致性同步
                        String oldWarehouseName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, WarehouseEnum.WAREHOUSE_NAME.getAttr(), "");
                        if (!Objects.equals(oldWarehouseName, newWarehouseName)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(warehouseEntityExt.getCorpid(), warehouseEntityExt.getId(), newWarehouseName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.WAREHOUSE);
                        }

                        break;
                    case PRODUCT:
                        String oldProductName = oldData.getString(ProductEnum.NAME.getAttr());
                        String oldProductNo = oldData.getString(ProductEnum.PRODUCT_NO.getAttr());
                        JSONObject childData = (JSONObject) paasFormDataEntity.getData().clone();
                        ProductEntityExt productEntityExt = new ProductEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, productEntityExt);
                        // 获取保存需要的参数map
                        JSONObject dataList = productEntityExt.getData();
                        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        List<StockNotifyPojo> stockNotifyList = productService.getSaveParam(dataList, supplierNameMap, warehouseNameMap);

                        opObjectName = dataList.getString(ProductEnum.NAME.getAttr());
                        // 如果是多规格产品保存时提示用户当前SPU下有SKU，需要开启规格字段后才能编辑保存。
                        Integer oldSpec = oldData.getInteger(ProductEnum.SPECIFICATION.getAttr());
                        JSONObject newSpecObj= FastJsonHelper.getJsonObjectOrDefaultFromFormData(dataList, ProductEnum.SPECIFICATION.getAttr(), new JSONObject());
                        boolean specChange = Objects.equals(oldSpec, 1) && !newSpecObj.getBooleanValue(ProductConstant.ADVANCED_MODE);
                        if (specChange) {
                            throw new XbbException(ProductErrorCodeEnum.API_ERROR_205042);
                        }
                        productService.formatParentProduct4Save(dataList,corpid, productEntityExt);
                        productFormDataService.setProductDefaultData(dataList);
                        String newProductNo = dataList.getString(ProductEnum.PRODUCT_NO.getAttr());
                        try{
                            if (Objects.equals(formDataUpdateDTO.getIsImport(),BasicConstant.ONE) && Objects.equals(formDataUpdateDTO.getIsCover(),BasicConstant.ONE)){
                                JSONArray product_imgs = (JSONArray) oldData.get(ProductEnum.PRODUCT_IMGS.getAttr());
                                dataList.put(ProductEnum.PRODUCT_IMGS.getAttr(),product_imgs);
                            }
                        }catch (Exception e) {
                            LOG.info(e.getMessage());
                        }
                        if (!dataList.containsKey(ProductEnum.COST.getAttr())){
                            dataList.put(ProductEnum.COST.getAttr(),oldData.get(ProductEnum.COST.getAttr()));
                        }
                        productEntityExt.setData(dataList);
                        productEntityExt.setCost(dataList.getDouble(ProductEnum.COST.getAttr()));
                        productEntityExt.setData(dataList);
                        updateLine = productModel.update(productEntityExt);
                        productEntityExt.setTotalCost(Arith.mul(data.getDouble(ProductEnum.STOCK.getAttr()),dataList.getDouble(ProductEnum.COST.getAttr())));
                        paasFormDataEntity.setId(productEntityExt.getId());
                        ((ProductEntityExt)oldPaasFormDataEntity).setNum(null);
                        ((ProductEntityExt)oldPaasFormDataEntity).setCost(null);
                        ((ProductEntityExt)oldPaasFormDataEntity).setTotalCost(null);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        // 被裹挟的产品封面图：有图片时第一张图片为封面图；无图片时删除封面图
                        JSONArray images = dataList.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr());
                        JSONArray thumbnails = new JSONArray();
                        if(images != null && images.size() > 0) {
                            thumbnails.add(images.get(0));
                            childData.put(ProductEnum.THUMBNAIL.getAttr(), thumbnails);
                        } else {
                            childData.put(ProductEnum.THUMBNAIL.getAttr(), thumbnails);
                            childData.put(ProductEnum.PRODUCT_IMGS.getAttr(), new JSONArray());
                        }
                        paasFormDataEntity.setData(childData);
                        // 保存子产品
                        // 临时入口,修改成本，统一修改分仓批次
//                        Double parentCost = productModel.getParentRealCost(corpid,dataId);
                        FieldAttrEntity fieldAttrEntity = formDataUpdateDTO.getExplainMap().get(ProductEnum.COST.getAttr());
//                        boolean updateCost = false;
//                        if (Objects.nonNull(fieldAttrEntity)){
//                            try {
                        Integer costAccuracy = Objects.isNull(fieldAttrEntity) ? null : fieldAttrEntity.getAccuracy();

//                                if (costAccuracy == null) {
//                                    costAccuracy = AttrDecimalPrecisionHelper.MAX_PRECISION;
//                                }
//                                Double molecule = parentCost;
//                                if (molecule == null) {
//                                    molecule = 0D;
//                                }
//                                Double denominator = saasUpdateHelp.getDoubleOrDefaultFromFormData(paasFormDataEntity.getData(), ProductEnum.COST.getAttr(), 0D);
//                                if (denominator == null) {
//                                    denominator = 0D;
//                                }
//                                if (Double.compare(Arith.round(molecule, costAccuracy), Arith.round(denominator, costAccuracy)) != 0) {
//                                    updateCost = true;
//                                }
//                                // 防止修改成本字段精度导致日志记录了成本发生变化
//                                // 17873 【产品】编辑产品后（未编辑成本），因为精度问题，自动修改了成本导致仓库成本不正确
//                                oldPaasFormDataEntity.getData().put(ProductEnum.COST.getAttr(), Arith.round(molecule, costAccuracy));
//                            } catch (Exception e) {
//                                LOG.info(e.getMessage());
//                            }
//                        }
                        Long oldCategoryId = FastJsonHelper.getLongOrDefaultFromFormData(oldData, ProductEnum.CATEGORY_ID.getAttr(), 0L);
                        Long categoryId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, ProductEnum.CATEGORY_ID.getAttr(), 0L);
                        Runnable runnable = () ->{
                            promotionActivityService.syncCategory(categoryId, productEntityExt.getId(), corpid);
                        };
                        threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
                        // 规格存在子产品中，拿子产品数据更新关联产品表的规格, 多规格的不可编辑规格，这里只处理单规格的
                        String oldSpecificationStr = null;
                        String newSpecificationStr = null;
                        try {
                            JSONObject specificationObj = childData.getJSONObject(ProductEnum.SPECIFICATION.getAttr());
                            Boolean advancedMode = specificationObj.getBoolean("advancedMode");
                            if (advancedMode != null && !advancedMode) {
                                newSpecificationStr = specificationObj.getString("specValue");
                                ChildProductDTO childProductDTO = new ChildProductDTO();
                                childProductDTO.setCorpid(corpid);
                                childProductDTO.setParentProductId(Collections.singletonList(productEntityExt.getId()));
                                PaasFormDataEsListVO esDataList = productService.getChildProductList(childProductDTO);
                                List<PaasFormDataEntityExt> paasFormDataESList = esDataList.getPaasFormDataESList();
                                if (Objects.nonNull(paasFormDataESList) && paasFormDataESList.size() > 0) {
                                    JSONObject childSingeData = paasFormDataESList.get(0).getData();
                                    oldSpecificationStr = childSingeData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                                }
                            }
                        } catch (Exception e) {
                            LOG.error("product update get specification fail", e);
                        }
                        productFormDataService.setProductDefaultData(childData);
                        childData.put(ProductEnum.WAREHOUSE.getAttr(),dataList.getJSONArray(ProductEnum.WAREHOUSE.getAttr()));
                        childData.put(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr(),dataList.getJSONArray(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr()));
                        childData.put(ProductEnum.SUPPLIER.getAttr(),dataList.getJSONArray(ProductEnum.SUPPLIER.getAttr()));
                        childData.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(),dataList.getJSONArray(ProductEnum.SUPPLIER_LINK_TEXT.getAttr()));
                        ChildProductVO childProductVO = productService.saveChildProduct(saasFormSaveDTO.getNewPaasFormDataEntity(), true, false, costAccuracy);

                        Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), saasFormSaveDTO.getCorpid());
                        if (isJxcUse) {
                            productService.associateWithSupplier(new ProductWithSupplierPojo(corpid, childProductVO, supplierNameMap, dataId));
                            ProductWithWarehousePojo productWithWarehousePojo = new ProductWithWarehousePojo(corpid, childProductVO, warehouseNameMap, dataId, stockNotifyList, false, dataList.getDouble(ProductEnum.COST.getAttr()));
                            BeanUtil.copyProperties(formDataUpdateDTO, productWithWarehousePojo);
                            if (Objects.nonNull(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo())) {
                                productWithWarehousePojo.setProductWarehouseSavePojo(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo().getProductWarehouseSavePojo());
                            }
                            Set<Long> existWarehouseIds = productService.associateWithWarehouse(productWithWarehousePojo);
//                            Set<String> existWarehouseIdStrings = existWarehouseIds.stream().map(x -> x + "").collect(Collectors.toSet());
//                            String[] warehouseIdArr = existWarehouseIdStrings.toArray(new String[existWarehouseIdStrings.size()]);
//                            // 需要更新仓库名称字段再说
//                            List<UpdateDataEntity> updateList = new ArrayList<>();
//                            JSONObject updateData = new JSONObject();
//                            updateData.put(ProductEnum.WAREHOUSE.getAttr(), warehouseIdArr);
//                            updateList.add(ExplainUtil.getUpdateData(productEntityExt.getId(),  updateData, corpid));
//                            List<ProductEntityExt> existProductList = childProductVO.getExistProductList();
//                            for (ProductEntityExt entityExt : existProductList) {
//                                updateData = new JSONObject();
//                                updateData.put(ProductEnum.WAREHOUSE.getAttr(), warehouseIdArr);
//                                updateList.add(ExplainUtil.getUpdateData(entityExt.getId(),  updateData, corpid));
//                            }
//                            productModel.updateBatch(updateList, corpid);

                            Integer oldBatchControl = getIntegerOrDefaultFromFormData(oldData, ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr(), 0);
                            Integer oldSerialNumberControl = getIntegerOrDefaultFromFormData(oldData, ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), 0);
                            Integer batchControl = getIntegerOrDefaultFromFormData(dataList, ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr(), 0);
                            Integer serialNumberControl = getIntegerOrDefaultFromFormData(dataList, ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), 0);
                            boolean oldShelfLifeDay = StringUtil.isEmpty(oldData.getString(ProductEnum.SHELF_LIFE_DAYS.getAttr()));
                            boolean shelfLifeDay = StringUtil.isEmpty(dataList.getString(ProductEnum.SHELF_LIFE_DAYS.getAttr()));
                            //编辑产品时需要判断是否开启或者关闭批次号,是否开启或者关闭序列号，是否开启或者关闭保质期（以是否为空为准）
                            Integer batchType = null;
                            Integer seqType = null;
                            Integer enableGuaranteePeriodType = null;
                            BatchSeqOperationEntity entity = new BatchSeqOperationEntity();
                            entity.setCorpid(corpid);
                            entity.setParentId(productEntityExt.getId());
                            if (oldBatchControl == 0 && batchControl == 1){
                                batchType = BatchSeqOperationEnum.ENABLEBATCH.getCode();
                                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(productEntityExt.getCorpid(), productEntityExt.getId(), 1);
                                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.BATCH_FLOW_BILL);
                            }else if (oldBatchControl == 1 && batchControl == 0){
                                batchType = BatchSeqOperationEnum.DISABLEBATCH.getCode();
                                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(productEntityExt.getCorpid(), productEntityExt.getId(), 0);
                                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.BATCH_FLOW_BILL);
                            }
                            if (Objects.nonNull(batchType)) {
                                entity.setType(batchType);
                                batchSeqOperationModel.insert(entity);
                            }
                            // 开启/关闭保质期
                            if (oldShelfLifeDay && !shelfLifeDay){
                                enableGuaranteePeriodType = BatchSeqOperationEnum.ENABLEGUARANTEEPERIOD.getCode();
                            }else if (!oldShelfLifeDay && shelfLifeDay){
                                enableGuaranteePeriodType = BatchSeqOperationEnum.DISABLEGUARANTEEPERIOD.getCode();
                            }
                            if (Objects.nonNull(enableGuaranteePeriodType)) {
                                entity.setType(enableGuaranteePeriodType);
                                batchSeqOperationModel.insert(entity);
                            }

                            // 序列号的开启/关闭
                            if (oldSerialNumberControl == 0 && serialNumberControl == 1){
                                seqType = BatchSeqOperationEnum.ENABLESEQ.getCode();
                                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(productEntityExt.getCorpid(), productEntityExt.getId(), 1);
                                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.SEQ_SEARCH);
                            }else if (oldSerialNumberControl == 1 && serialNumberControl == 0){
                                seqType = BatchSeqOperationEnum.DISABLESEQ.getCode();
                                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(productEntityExt.getCorpid(), productEntityExt.getId(), 0);
                                consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.SEQ_SEARCH);
                            }
                            if (Objects.nonNull(seqType)) {
                                entity.setType(seqType);
                                batchSeqOperationModel.insert(entity);
                            }
                        }
                        saasFormSaveDTO.setChildProductVO(childProductVO);
                        productService.afterSave(saasFormSaveDTO);


                        //父产品的名称和编号更新
                        if (!Objects.equals(oldProductName, opObjectName) || !Objects.equals(oldProductNo, newProductNo) || !Objects.equals(oldSpecificationStr, newSpecificationStr)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(productEntityExt.getCorpid(), productEntityExt.getId(), opObjectName, null, newSpecificationStr, newProductNo);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.PRODUCT);
                        }


                        // 记录日志
                        String productNo = dataList.getString(ProductEnum.PRODUCT_NO.getAttr());
                        opObjectName = opObjectName == null ? productNo : sb.append(opObjectName).append("（").append(productNo).append("）").toString();
                        // bug 26128
                        dataList.put(ProductEnum.WAREHOUSE.getAttr(), dataList.getJSONArray(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr()));
                        oldData.put(ProductEnum.WAREHOUSE.getAttr(), oldData.getJSONArray(ProductEnum.WAREHOUSE_LINK_TEXT.getAttr()));
                        // 26467
                        productEntityExt.getData().put(ProductEnum.INSTRUCTION.getAttr(), paasFormDataEntity.getData().getString(ProductEnum.INSTRUCTION.getAttr()));
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(productEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PRODUCT;
                        break;
                    case ASSEMBLE:
                        JSONObject assembleData = (JSONObject) paasFormDataEntity.getData().clone();
                        AssembleEntityExt assembleEntityExt = new AssembleEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, assembleEntityExt);
                        // 关联产品特殊处理
                        JSONObject assembleDataList = assembleEntityExt.getData();
                        JSONArray outProductArray = saasSaveHelp.formatSelectProduct4Save2(assembleDataList, AssembleEnum.OUT_PRODUCTS.getAttr());
                        JSONArray inProductArray = saasSaveHelp.formatSelectProduct4Save2(assembleDataList, AssembleEnum.IN_PRODUCTS.getAttr());
                        assembleEntityExt.setData(assembleDataList);

                        updateLine = assembleModel.update(assembleEntityExt);
                        assembleData.put(AssembleEnum.OUT_PRODUCTS.getAttr(),outProductArray);
                        assembleData.put(AssembleEnum.IN_PRODUCTS.getAttr(),inProductArray);
                        paasFormDataEntity.setData(assembleData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        assembleService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(assembleEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.ASSEMBLE;
                        break;
                    case INSTOCK:
                    case PURCHASE_INSTOCK:
                    case REFUND_INSTOCK:
                    case OTHER_INSTOCK:
                    case PRODUCTION_INSTOCK:
                    case RETURNED_MATERIEL_INSTOCK:
                        JSONObject instockData = (JSONObject) paasFormDataEntity.getData().clone();
                        InstockEntityExt instockEntityExt = new InstockEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, instockEntityExt);
                        // 关联产品特殊处理
                        JSONObject instockDataList = instockEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(instockDataList, InstockEnum.PRODUCT.getAttr());
                        instockEntityExt.setData(instockDataList);

                        updateLine = instockModel.update(instockEntityExt);
//                        paasFormDataEntity.setId(instockEntityExt.getId());
//                        instockData.put(InstockEnum.PRODUCT.getAttr(),productArray);
//                        paasFormDataEntity.setData(instockData);
//                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
//                        instockService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(instockEntityExt));
                        operateModuleTypeEnum = InstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum();
                        break;
                    case OUTSTOCK:
                    case CONTRACT_OUTSTOCK:
                    case OTHER_OUTSTOCK:
                    case RETURNED_PURCHASE_OUTSTOCK:
                    case WORK_ORDER_OUTSTOCK:
                    case PRODUCTION_MATERIEL_OUTSTOCK:
                        JSONObject outstockData = (JSONObject) paasFormDataEntity.getData().clone();
                        OutstockEntityExt outstockEntityExt = new OutstockEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, outstockEntityExt);
                        // 关联产品特殊处理
                        JSONObject outstockDataList = outstockEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(outstockDataList, OutstockEnum.PRODUCT.getAttr());
                        outstockEntityExt.setData(outstockDataList);

                        updateLine = outstockModel.update(outstockEntityExt);
                        paasFormDataEntity.setId(outstockEntityExt.getId());

                        // 保存后操作
                        outstockData.put(OutstockEnum.PRODUCT.getAttr(),productArray);
                        paasFormDataEntity.setData(outstockData);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        outstockService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = serialNo;
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(outstockEntityExt));
                        operateModuleTypeEnum = OutstockTypeEnum.getByStockBusinessType(businessType).getOperateModuleTypeEnum();
                        break;
                    case REFUND:
                        RefundEntityExt refundEntityExt = new RefundEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, refundEntityExt);
                        // 关联产品特殊处理
                        JSONObject refundDataList = refundEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(refundDataList, RefundEnum.PRODUCTS.getAttr());
                        JSONArray invoiceArray = refundDataList.getJSONArray(RefundEnum.INVOICES.getAttr());
                        JSONArray paymentSheetArray = refundDataList.getJSONArray(RefundEnum.PAYMENT_SHEETS.getAttr());
                        JSONArray paymentArray = refundDataList.getJSONArray(RefundEnum.PAYMENTS.getAttr());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.INVOICES.getAttr(), RefundEnum.INVOICES_LINKED_TEXT.getAttr(), RefundEnum.INVOICES.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.PAYMENT_SHEETS.getAttr(), RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENT_SHEETS.getFieldType());
                        saasSaveHelp.formatLinkBusiness4SaveBySerialNo(data, RefundEnum.PAYMENTS.getAttr(), RefundEnum.PAYMENTS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENTS.getFieldType());
                        refundEntityExt.setData(refundDataList);
                        updateLine = refundModel.update(refundEntityExt);
                        paasFormDataEntity.getData().put(RefundEnum.PRODUCTS.getAttr(),productArray);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        PaasFormEntity paymentSheetFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid, distributorMark, null);
                        PaasFormEntity invoiceFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.INVOICE.getCode(), corpid, distributorMark, null);
                        boolean paymentSheetIsProcess = Objects.equals(paymentSheetFormEntity.getIsProcessForm(), BasicConstant.ONE);
                        boolean invoiceIsProcess = Objects.equals(invoiceFormEntity.getIsProcessForm(), BasicConstant.ONE);
                        AssociatedBusinessAfterSavePojo refundAfterSavePojo = new AssociatedBusinessAfterSavePojo(invoiceArray, paymentSheetArray, paymentArray, null, reRollBackEntity, paymentSheetIsProcess, invoiceIsProcess);
                        refundService.afterSave(saasFormSaveDTO, refundAfterSavePojo);
                        // 记录日志
                        opObjectName = data.getString(RefundEnum.REFUND_NAME.getAttr());
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(refundEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.REFUND;
                        break;
                    case QUOTATION:
                        QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, quotationEntityExt);
                        // 关联产品特殊处理
                        JSONObject quotationDataList = quotationEntityExt.getData();
                        productArray = saasSaveHelp.formatSelectProduct4Save2(quotationDataList, RefundEnum.PRODUCTS.getAttr());
                        quotationEntityExt.setData(quotationDataList);
                        updateLine = quotationModel.update(quotationEntityExt);
                        paasFormDataEntity.getData().put(RefundEnum.PRODUCTS.getAttr(),productArray);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        saasFormSaveDTO.setIsNew(false);
                        quotationService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = data.getString(QuotationEnum.NAME.getAttr());
                        opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(quotationEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.QUOTATION;
                        break;
                    case PAYMENT_SHEET:
                        SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAYMENT_SHEET);
                        data = fundHelp.handlePaymentSheetData4Update(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
                        paasFormDataEntity.setData(data);
                        PaymentSheetEntityExt paymentSheetEntityExt = new PaymentSheetEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, paymentSheetEntityExt);
                        updateLine = paymentSheetModel.update(paymentSheetEntityExt);
                        //更新子单信息
                        List<UpdateDataEntity> updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, saasFormSaveDTO.getAmountDetail(), formDataUpdateDTO.getExplainMap(), formDataUpdateDTO.getDistributorMark());
                        if (CollectionsUtil.isNotEmpty(updateList)) {
                            paymentSheetModel.updateBatch(updateList, corpid);
                        }
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        // 记录日志
                        opObjectName = serialNo;
                        // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                        paymentSheetEntityExt.setOwnerId(null);
                        paymentSheetEntityExt.setDepartmentId(null);
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentSheetEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                        break;
                    case PAY_SHEET:
                        sheetTypeEnum = SheetTypeEnum.getByCodeRefTypeEnum(data.getString(PaySheetEnum.PAY_SHEET_TYPE.getAttr()), XbbRefTypeEnum.PAY_SHEET);
                        data = fundHelp.handlePaymentSheetData4Update(sheetTypeEnum, data, oldData, formDataUpdateDTO.getDistributorMark(), null);
                        paasFormDataEntity.setData(data);
                        PayPlanSheetEntityExt payPlanSheetEntityExt = new PayPlanSheetEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, payPlanSheetEntityExt);
                        updateLine = payPlanSheetModel.update(payPlanSheetEntityExt);
                        //更新子单信息
                        updateList = saasUpdateHelp.updateSonDataList4Sheet(corpid, sheetTypeEnum, saasFormSaveDTO.getAmountDetail(), formDataUpdateDTO.getExplainMap(), formDataUpdateDTO.getDistributorMark());
                        if (CollectionsUtil.isNotEmpty(updateList)) {
                            payPlanSheetModel.updateBatch(updateList, corpid);
                        }
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        // 记录日志
                        opObjectName = serialNo;
                        // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                        payPlanSheetEntityExt.setOwnerId(null);
                        payPlanSheetEntityExt.setDepartmentId(null);
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(payPlanSheetEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.PayManage;
                        break;
                    case PAYMENT_TASK:
                        PaymentTaskEntityExt paymentTaskEntityExt = new PaymentTaskEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, paymentTaskEntityExt);
                        updateLine = paymentTaskModel.update(paymentTaskEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        //paymentTaskService.afterSave(saasFormSaveDTO);
                        // 记录日志
                        opObjectName = paymentTaskEntityExt.getSerialNo();
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paymentTaskEntityExt));
//                        operateModuleTypeEnum = OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET;
                        operateModuleTypeEnum = OperateModuleTypeEnum.PaymentManage;
                        break;
                    case CLUE:
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.COMPANY_NAME.getAttr(), "");
                        ClueEntityExt clueEntityExt = new ClueEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, clueEntityExt);
                        updateLine = clueModel.update(clueEntityExt);
                        paasFormDataEntity.setUpdateTime(clueEntityExt.getUpdateTime());
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        clueService.afterSave(saasFormSaveDTO);
                        marketActivityForStaticHelp.updateMarketActivity(paasFormDataEntity, redundantTemplateTypeEnum);
                        // 数据一致性同步
                        String oldCompanyName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, ClueEnum.COMPANY_NAME.getAttr(), "");
                        if (!Objects.equals(oldCompanyName, opObjectName)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), opObjectName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.CLUE);
                        }
                        // 记录日志
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(clueEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.CLUE;
                        break;
                    case MARKET_ACTIVITY:
                        opObjectName = FastJsonHelper.getStringOrDefaultFromFormData(data, MarketActivityEnum.NAME.getAttr(), "");
                        MarketActivityEntityExt marketActivityEntityExt = new MarketActivityEntityExt();
                        BeanUtil.copyProperties(paasFormDataEntity, marketActivityEntityExt);
                        updateLine = marketActivityModel.update(marketActivityEntityExt);
                        packageSaasFormUpdateSaveDTO(saasFormSaveDTO, paasFormDataEntity, oldPaasFormDataEntity);
                        marketActivityService.afterSave(saasFormSaveDTO);
                        marketActivityForStaticHelp.updateMarketActivity(paasFormDataEntity,redundantTemplateTypeEnum);

                        // 数据一致性同步
                        String oldName = FastJsonHelper.getStringOrDefaultFromFormData(oldData, MarketActivityEnum.NAME.getAttr(), "");
                        if (!Objects.equals(oldName, opObjectName)) {
                            ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(paasFormDataEntity.getCorpid(), paasFormDataEntity.getId(), opObjectName);
                            consistencySyncProducer.syncData(consistencySyncRabbitMqDTO, XbbRefTypeEnum.MARKET_ACTIVITY);
                        }
                        // 记录日志
                        newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(marketActivityEntityExt));
                        operateModuleTypeEnum = OperateModuleTypeEnum.MARKET_ACTIVITY;
                        break;
                    default:
                        throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
                }

                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataUpdateDTO.getExplainMap(), data, new JSONObject(), corpid, dataId, businessType, userId);
            }
            afterSaveVO.setSuccess(updateLine);
            if(!isCoverage){
                String memoName = Objects.isNull(paasFormEntityExt) ? "" : paasFormEntityExt.getName();
                if(Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.CUSTOMER)){
                    String isPublic = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), "");
                    memoName = Objects.equals(isPublic, "1") ? PublicEnum.PUBLIC.getName() : redundantTemplateTypeEnum.getName();
                }

                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_WORK), userName, memoName, opObjectName);
                if(Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.PAYMENT)){
                    // 负责人是获取当前登录人的ID，不准确,所属部门也没有模版字段，舍去
                    oldPaasFormDataEntity.setOwnerId(null);
                    oldPaasFormDataEntity.setDepartmentId(null);
                }
                JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldPaasFormDataEntity));

                Long clueId = formDataUpdateDTO.getClueId();
                if(clueId != null && clueId > 0 && Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.CUSTOMER)){
                    // 客户来自于线索转换
                    ClueEntityExt clueEntityExt = clueModel.getByKey(clueId, corpid);
                    JSONObject clueObj = clueEntityExt.getData();
                    String clueName = FastJsonHelper.getStringOrDefaultFromFormData(clueObj, ClueEnum.COMPANY_NAME.getAttr(), "");
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_CLUE_TRANS_CUSTOMER), userName, clueName, memoName, opObjectName);

                    List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, formDataUpdateDTO.getExplainMap(), oldObj, newObj);
                    mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, operateModuleTypeEnum, OperateTypeEnum.TRANSFORM,
                            formDataUpdateDTO.getDataId().toString(), opObjectName, memo, formDataUpdateDTO.getHttpHeader());
                } else {
                    List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, formDataUpdateDTO.getExplainMap(), oldObj, newObj);
                    mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, operateModuleTypeEnum, OperateTypeEnum.EDIT,
                            formDataUpdateDTO.getDataId().toString(), opObjectName, memo, formDataUpdateDTO.getHttpHeader());
                }
            }
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200019.getMsg(),e);
            // 老数据去除data内的无用无映射字段
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.UPDATETIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.CREATORID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.ADDTIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
            proEsHelper.reductionEsInUpdate(oldPaasFormDataEntity,oldPaasFormDataEntity.getId(),oldPaasFormDataEntity.getCorpid(), businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw e;
        }catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200019.getMsg(),e);
            // 老数据去除data内的无用无映射字段
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.UPDATETIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.CREATORID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.ADDTIME.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.OWNERID.getAlias());
            oldPaasFormDataEntity.getData().remove(FieldTypeEnum.SERIALNO.getAlias());
            proEsHelper.reductionEsInUpdate(oldPaasFormDataEntity,oldPaasFormDataEntity.getId(),oldPaasFormDataEntity.getCorpid(), businessType,saasMark);
            String type = String.valueOf(businessType);
            Runnable runnable = () -> {
                try {
                    proEsHelper.otherRefEsDataRollBack(paasFormDataEntity,corpid,type,saasMark, reRollBackEntity);
                } catch (Exception e2) {
                    LOG.error("回滚其他表数据失败", e2);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200019);
        }
        return afterSaveVO;
    }


    @Override
    public PaasFormDataEntity getOldPaasFormDataEntity(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        Integer saasMark = formDataUpdateDTO.getSaasMark();
        Long dataId = formDataUpdateDTO.getDataId();
        String corpid = formDataUpdateDTO.getCorpid();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        PaasFormDataEntity oldPaasFormDataEntity = null;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            oldPaasFormDataEntity = paasFormDataModel.getByKey(dataId, corpid);
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = saasUpdateHelp.getFormData(dataId, corpid, businessType);
            if (paasFormDataEntityExt != null) {
                oldPaasFormDataEntity = paasFormDataEntityExt;
            }
        }
        if (oldPaasFormDataEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return oldPaasFormDataEntity;
    }

    @Override
    public PaasFormDataEntity getFormDataEntity(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        PaasFormDataEntity paasFormDataEntity = null;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            paasFormDataEntity = paasFormDataModel.getByKey(dataId, corpid);
        } else {
            PaasFormDataEntityExt paasFormDataEntityExt = saasUpdateHelp.getFormData(dataId, corpid, businessType);
            if (paasFormDataEntityExt != null) {
                paasFormDataEntity = paasFormDataEntityExt;
            }
        }
        if (paasFormDataEntity == null) {
            LOG.error("获取表单数据异常，corpid={}，dataId={}，businessType={}，saasMark={}", corpid, dataId, businessType, saasMark);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return paasFormDataEntity;
    }

    @Override
    public Long insertWorkOrder(FormDataAddDTO formDataAddDTO, WorkOrderEntity workOrderEntity) throws XbbException {
        Long dataId = 0L;
        Integer businessType = formDataAddDTO.getBusinessType();
        String corpid = formDataAddDTO.getCorpid();
        try {
            if (businessType == null || businessType == 0) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 工单data中移除负责人和协同人
            JSONObject conProductDataList = workOrderEntity.getData();
            conProductDataList.remove(FieldTypeEnum.OWNERID.getAlias());
            conProductDataList.remove(FieldTypeEnum.COUSERID.getAlias());
            conProductDataList.remove(FieldTypeEnum.SERIALNO.getAlias());
            JSONObject workOrderDataObj = (JSONObject) workOrderEntity.getData().clone();
            SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
            BeanUtil.copyProperties(formDataAddDTO, saasFormSaveDTO);
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            // TODO: 2019/4/12 不知道干什么用,先留着  @author 魏荣杰  @date 2019/4/12 11:21
            SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo = formDataAddDTO.getSaasNeedRedundantAttrPoJo();
            if (redundantTemplateTypeEnum == RedundantTemplateTypeEnum.WORKORDER) {
                //关联的产品特殊处理
                JSONArray productArray = saasSaveHelp.formatSelectProduct4Save2(conProductDataList, WorkOrderEnum.SPARE_PARTS.getAttr());
                workOrderEntity.setData(conProductDataList);
                workOrderModel.insert(workOrderEntity);
                dataId = workOrderEntity.getId();
                saasFormSaveDTO.setIsNew(true);
                saasFormSaveDTO.setOldData(workOrderDataObj);
                saasFormSaveDTO.setNewData(workOrderDataObj);
                workOrderEntity.getData().put(WorkOrderEnum.SPARE_PARTS.getAttr(),productArray);
                saasFormSaveDTO.setOldWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setNewWorkOrderEntity(workOrderEntity);
                saasFormSaveDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPojo);
                workOrderService.afterSave(saasFormSaveDTO);

                //文件柜数据保存
                cabinetFileService.saveDataCabinetFile(formDataAddDTO.getExplainMap(), workOrderDataObj, workOrderEntity.getSubFormData(), formDataAddDTO.getCorpid(), dataId, XbbRefTypeEnum.WORK_ORDER.getCode(), formDataAddDTO.getUserId());
            } else {
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }
        } catch (XbbException e) {
            LOG.warn(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,SaasMarkEnum.SAAS.getCode());
            throw e;
        } catch (Exception e){
            LOG.error(BuinessDefaultErrorCodeEnum.API_ERROR_200018.getMsg(),e);
            proEsHelper.physicalDeleteAllInAdd(dataId,corpid,businessType,SaasMarkEnum.SAAS.getCode());
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200018);
        }

        String serialNo = workOrderEntity.getSerialNo();
        String opName = RedundantTemplateTypeEnum.WORKORDER.getName();
        String userId = formDataAddDTO.getUserId();
        String creatorId = workOrderEntity.getCreatorId();
        String creatName = "";
        if(creatorId != null){
            // 走审批时获取创建人id
            UserEntity user = userModel.getByKeyIngoreDel(creatorId, corpid);
            creatName = Objects.isNull(user) ? "" : user.getName();
        }
        String userName = Objects.equals(workOrderEntity.getFlowStatus(), 2) ? creatName : formDataAddDTO.getLoginUserName();
        if (Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID_PARAM) || Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID)) {
            userName = PaasConstant.OUT_LINK_USER_NAME;
        }
        userId = Objects.equals(workOrderEntity.getFlowStatus(), 2) ? creatorId : userId;
        //记录日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, opName, serialNo);
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.WORK, OperateTypeEnum.NEW,
                workOrderEntity.getId().toString(), serialNo, memo, formDataAddDTO.getHttpHeader());

        return dataId;
    }

    @Override
    public WorkOrderEntity getOldWorkOrderEntity(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, corpid);
        if (workOrderEntity == null || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return workOrderEntity;
    }

    @Override
    public void updateFormDataStatus(PaasProcessDataEntity paasProcessDataEntity, Integer flowStatus) throws XbbException {
        formDataHelp.updateFormDataStatus(paasProcessDataEntity, flowStatus);
    }

}
